Search code examples
c++templatesc++11rvalue-reference

Template references type deducion


I have a template function:

template<typename T>
void doSomething(T& value) {
    // doSomething here
}

All is ok, but passing r-value references:

doSomething(getTempVal());

Producing no matching function for call error, because particular instantiated function template expects an l-value for 1st argument. Is there any workarounds to allow template function taking both lvalue and rvalue references without adding new template?


Solution

  • Yes, just use && instead of &.

    It may seem odd, because you might think that this would disallow calling it with lvalues, but actually, if T is itself an lvalue reference type, then T && is just T: it doesn't become an rvalue reference type.

    In other words,

    template <typename T>
    void f(T &&);
    
    int main() {
      int k = 1;
      f(k); // okay: calls f<int&>
      f(2); // okay: calls f<int>
    }
    

    Note that T can be deduced as a reference type, and the function body will need to be made to handle that.