Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ rvalue temporaries in template

Can you please explain me the difference between mechanism of the following:

int function();

template<class T>
void function2(T&);

void main() {
    function2(function()); // compiler error, instantiated as int &

    const int& v = function();
    function2(v); // okay, instantiated as const int&
}

is my reasoning correct with respect to instantiation? why is not first instantiated as const T&?

Thank you

like image 353
Anycorn Avatar asked Jun 08 '10 05:06

Anycorn


1 Answers

Because function returns a non-const value. Only objects can be const, because they store some state that could be modified if it weren't const. What you return there is not an object, but a pure value. Conceptually, they are not modifiable (like enumeration constants, for example), but they are not const qualified (like, again, enumeration constants).

like image 190
Johannes Schaub - litb Avatar answered Oct 05 '22 18:10

Johannes Schaub - litb