Search code examples
c++c++14autotype-deductiondecltype-auto

Are there any realistic use cases for `decltype(auto)` variables?


Both from my personal experience and from consulting answers to questions like What are some uses of decltype(auto)? I can find plenty of valuable use cases for decltype(auto) as a function return type placeholder.

However, I am seriously struggling to think of any valid (i.e. useful, realistic, valuable) use case for decltype(auto) variables. The only possibility that comes to mind is to store the result of a function returning decltype(auto) for later propagation, but auto&& could be used there as well and it would be simpler.

I've even searched throughout all my projects and experiments, and the 391 occurrences of decltype(auto) are all return type placeholders.

So, are there any realistic use cases for decltype(auto) variables? Or it this feature only useful when used as a return type placeholder?


How do you define "realistic"?

I am looking for a use case that provides value (i.e. it's not just an example to show how the feature works) where decltype(auto) is the perfect choice, compared to alternatives such as auto&& or to not declaring a variable at all.

The problem domain doesn't matter, it could be some obscure metaprogramming corner case or arcane functional programming construct. However, the example would need to make me go "Hey, that's clever/beautiful!" and using any other feature to achieve the same effect would require more boilerplate or have some sort of drawback.


Solution

  • Probably not a very deep answer, but basically decltype(auto) was proposed to be used for return type deduction, to be able to deduce references when the return type is actually a reference (contrary to plain auto that will never deduce the reference, or auto&& that will always do it).

    The fact that it can also be used for variable declaration not necessarily means that there should be better-than-other scenarios. Indeed, using decltype(auto) in variable declaration will just complicate the code reading, given that, for a variable declaration, is has exactly the same meaning. On the other hand, the auto&& form allows you to declare a constant variable, while decltype(auto) doesn't.