I have a sample code below.
#include<iostream>
template<typename T>
class XYZ
{
private:
T & ref;
public:
XYZ(T & arg):ref(arg)
{
}
};
class temp
{
int x;
public:
temp():x(34)
{
}
};
template<typename T>
void fun(T & arg)
{
}
int main()
{
XYZ<temp> abc(temp());
fun(temp()); //This is a compilation error in gcc while the above code is perfectly valid.
}
In the above code even though XYZ constructor takes argument as non const reference, it compiles fine while the fun function fails to compile. Is this specific to g++ compiler or c++ standard has to say something about it?
Edit:
g++ -v gives this.
gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)
It compiles, because it is NOT a variable declaration. I’m sure you think its a variable declaration when the fact is that its a function declaration. The name of the function is
abc; the function returns an object of typeXYZ<temp>and takes a single (unnamed) argument which in turn is a function returning typetempand taking no argument. See these topics for detail explanation:And
fun(temp())doesn’t compile, becausetemp()creates a temporary object and a temporary object cannot be bound to non-const reference.So the fix is this : define your function template as: