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
Because
functionreturns 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).