C ++模板:隐式转换,没有匹配函数调用ctor [英] C++ Templates: implicit conversion, no matching function for call to ctor

查看:267
本文介绍了C ++模板:隐式转换,没有匹配函数调用ctor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

        test(T& e)
        {
        }

};

int main()
{

    test<double> d(4.3);

    return 0;
}

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

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

但是,这样工作:

double a=1.1;
test<double> d(a);

为什么会这样?
有可能g ++不能隐式地将文字表达式1.1转换为double?
谢谢。

Why is this happing? Is it possible that g++ cannot implicitly convert literal expression 1.1 to double? Thanks.

推荐答案

你传递双重 1.1 到非const引用 T& 。这意味着你必须向构造函数传递一个有效的左值,例如:

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);

使构造函数接受const引用( const T& )和它的工作原理,因为你被允许绑定临时(rvalues)到const引用,4.3技术上是一个临时双。

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.

这篇关于C ++模板:隐式转换,没有匹配函数调用ctor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆