C++模板:隐式转换,没有用于调用ctor的匹配函数

non*_*ame 3 c++ templates constructor

template<class T>
class test
{
    public:
        test()
        {
        }

        test(T& e)
        {
        }

};

int main()
{

    test<double> d(4.3);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用g ++ 4.4.1编译时出现以下错误:

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
Run Code Online (Sandbox Code Playgroud)

但是,这有效:

double a=1.1;
test<double> d(a);
Run Code Online (Sandbox Code Playgroud)

为什么会这么讨厌?是否有可能g ++无法将文字表达式1.1隐式转换为double?谢谢.

Ash*_*ain 8

您将double 1.1传递给非const引用T&.这意味着您必须将有效的左值传递给构造函数,例如:

double x = 4.3;
test<double> d(x);
Run Code Online (Sandbox Code Playgroud)

使构造函数采用const引用(const T&)并且它可以工作,因为允许将临时值(rvalues)绑定到const引用,并且4.3在技术上是临时双精度.