Search code examples
c++c++11lambdaautotemplate-argument-deduction

What is the easiest way to create a local variable with the same type as a deduced argument?


Namely:

[](auto const& foo) {
    ??? bar; // should be same base type as foo, minus const&
}

So far, I'm using:

typename std::remove_const<typename std::remove_reference<decltype(foo)>::type>::type combination

But I'm really hoping theres an easier alternative!


Solution

  • std::decay<decltype(whatever)>::type, or decay_t if your std library has been updated with it.

    It emulates various kinds of function argument decays. It handles if your arg was a reference-to-function. On reference-to-array, it produces a pointer as well, which is less ideal.

    If you want to handle those differently, you'll have to roll your own.