【问题标题】:C++ Templates: implicit conversion, no matching function for call to ctorC++ 模板:隐式转换,对 ctor 的调用没有匹配的函数
【发布时间】:2010-04-13 10:09:55
【问题描述】:
template<class T>
class test
{
    public:
        test()
        {
        }

        test(T& e)
        {
        }

};

int main()
{

    test<double> d(4.3);

    return 0;
}

使用 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

但是,这是可行的:

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

为什么会这样? g++ 是否有可能无法将文字表达式 1.1 隐式转换为双精度? 谢谢。

【问题讨论】:

  • 你的构造函数不需要双精度,它需要一个双精度引用。

标签: c++ templates constructor


【解决方案1】:

您将双精度 1.1 传递给非常量引用 T&amp;。这意味着您必须将有效的左值传递给构造函数,例如:

double x = 4.3;
test<double> d(x);

使构造函数采用 const 引用 (const T&amp;) 并且它可以工作,因为您可以将临时变量(右值)绑定到 const 引用,并且 4.3 在技术上是一个临时的 double。

【讨论】:

    【解决方案2】:

    这是由于您的构造函数定义中的引用 (&amp;)。您不能像这样通过引用传递常量值,只能像第二个示例中那样传递变量。

    【讨论】:

      【解决方案3】:

      您不能将双精度字面量绑定到(非常量)双精度&。

      您的意思是将其作为 T const& 还是按值传递? (两者都适用于您目前提供的代码。)

      【讨论】:

        【解决方案4】:

        您不能对临时对象进行非常量引用。尝试将您的构造函数更改为

            test(const T& e)
            {
            }
        

        或按值传递:

            test(T e)
            {
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-11
          • 1970-01-01
          • 2013-01-26
          相关资源
          最近更新 更多