In particular in generic code, auto ref variables that infer ref if and only if the initializer is an lvalue could be quite valuable. The same is true for foreach over ranges, where the foreach variable would infer ref if front is an lvalue (be it a variable or a function that returns by reference) and lastly, for conditions, if (auto ref x = f()) could infer ref from the value category of the initializer, like any other variable.
In my opinion, this is an obvious no-brainer because generic code can’t know if a type is expensive to copy or even copyable, and taking lvalues by reference and rvalues by value is the obvious right way.
In contrast to function parameters, auto ref for local variables, foreach variables, and if condition variables requires no template context and could be a way for a programmer to express: Just store the value, don’t (needlessly) copy it, similar to C++’s auto&&, which, too, works for local variables, loop variables, etc. and not only function template parameters.
The same way __traits(isRef) works for auto ref function template parameters, it should work for local variables, too.
Permalink
Reply