Template overload (reference and non-reference)

I have a seemingly simple question that I do not know how to solve.

Imagine the following method template

template<typename T> void Add(T& var); 

where specializations can add something to the container (sort of). I can pass the POD or more complex types, such as strings , and that's why I give T as a reference.

The problem is that whenever I want to call the Add (...) with the result of another method, for example:

 Add(MethodThatReturnsAnInt()); 

It will not work, and to save the result MethodThatReturnsAnInt() requires a temporary variable.

Is there a way to overload Add , so I had a reference transfer and non-reference version?

 template<typename T> void Add(T& var); template<typename T> void Add(T var); 

will std::enable_if be used in this situation?

+5
source share
2 answers

If you have a C ++ compiler 11, you can use the link (Universal the Reference) :

 template<typename T> void Add(T&& var) {} int MethodThatReturnsAnInt() { return 42; } int main() { int a = MethodThatReturnsAnInt(); Add(a); // lvalue passed: void Add(int& var) takes lvalue reference Add(MethodThatReturnsAnInt()); // rvalue passed: void Add(int&& var) takes rvalue reference } 

T&& is not link at rvalue in this example. In the context of the withdrawal of type T&& it is of particular importance. T depends on the expression passed to the function Add() as follows:

  • If lvalue expression (for example: a ) the type of E , what is displayed on T E& .

  • If rvalue expression (for example, the return value of the function) type E , then T is displayed on the E , and var will be of type E&& .

+6
source

If your compiler does not yet support the C ++ 11, you will need to update your compiler, and then use the forward link && .

+2
source

All Articles