问题
template<class T>
class test
{
public:
test()
{
}
test(T& e)
{
}
};
int main()
{
test<double> d(4.3);
return 0;
}
Compiled using g++ 4.4.1 with the following errors:
g++ test.cpp -Wall -o test.exe
test.cpp: In function 'int main()':
test.cpp:18: error: no matching function for call to 'test<double>::test(double)
'
test.cpp:9: note: candidates are: test<T>::test(T&) [with T = double]
test.cpp:5: note: test<T>::test() [with T = double]
test.cpp:3: note: test<double>::test(const test<double>&)
make: *** [test.exe] Error 1
However, this works:
double a=1.1;
test<double> d(a);
Why is this happing? Is it possible that g++ cannot implicitly convert literal expression 1.1 to double? Thanks.
回答1:
You're passing the double 1.1 to a non-const reference T&. This means you'd have to pass a valid lvalue to the constructor such as by doing:
double x = 4.3;
test<double> d(x);
Make the constructor take a const reference (const T&) and it works, because you are allowed to bind temporaries (rvalues) to const references, and 4.3 is technically a temporary double.
回答2:
It's due to the reference (&) in your constructor definition. You can't pass a constant value by reference like that, only a variable like in your second example.
回答3:
You cannot bind a double literal to a (non-const) double&.
Did you mean to pass it as a T const& or by value instead? (Either works for the code you've given so far.)
回答4:
You can't take a non-const reference to a temporary. Try changing your constructor to
test(const T& e)
{
}
or pass by value:
test(T e)
{
}
来源:https://stackoverflow.com/questions/2628646/c-templates-implicit-conversion-no-matching-function-for-call-to-ctor