【问题标题】:Default vs Deduced template parameter?默认与推导模板参数?
【发布时间】:2012-11-18 06:49:45
【问题描述】:

如下:

template<typename Type>
struct MyClass
{
    template<typename OtherType> MyClass(const MyClass<OtherType>& x);
    template<typename OtherType = Type> void test(const MyClass<OtherType>& x);
};

在函数test之间做了什么:

案例1:默认参数为priority:隐式调用转换构造函数MyClass&lt;Type&gt;(const MyClass&lt;OtherType&gt;&amp; x),调用MyClass&lt;Type&gt;::test&lt;Type&gt;(const MyClass&lt;Type&gt;&amp; x)

案例2:推导出的参数是优先级:MyClass&lt;Type&gt;::test&lt;Type&gt;(const MyClass&lt;OtherType&gt;&amp; x)被调用。


我认为好的答案是第二个,但我不确定。您能否向我确认(并且这种情况已被标准明确定义)?


编辑:测试函数被调用:

MyClass<double> d;
MyClass<unsigned int> ui;
d.test(ui); // <- So the question is : is ui implicitely 
            //    converted to MyClass<double> or not ?

【问题讨论】:

    标签: c++ c++11 templates standards-compliance template-argument-deduction


    【解决方案1】:

    test 将被称为

    MyClass<double>::test(const MyClass<unsigned int> &)
    

    即不会将uiMyClass&lt;unsigned int&gt; 转换为MyClass&lt;double&gt;

    默认模板参数永远不会覆盖给定的参数。仅在没有给出模板参数且编译器无法从函数参数中推断出来时使用。

    来自 C++11 标准:

    (§14.8.2/5) 得到的替换和调整的函数类型用作模板参数推导的函数模板的类型。如果没有推导出模板参数,则使用其默认模板参数(如果有)。 [ 例子:

    template <class T, class U = double>
    void f(T t = 0, U u = 0);
    void g() {
      f(1, ’c’);      // f<int,char>(1,’c’)
      f(1);           // f<int,double>(1,0)
      f();            // error: T cannot be deduced
      f<int>();       // f<int,double>(0,0)
      f<int,char>();  // f<int,char>(0,0)
    }
    

    —结束示例]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 2023-01-24
      • 2020-02-27
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 2020-11-02
      相关资源
      最近更新 更多