繁体   English   中英

默认与推导的模板参数?

[英]Default vs Deduced template parameter?

在下面的 :

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:默认参数是优先级:隐式调用转换构造函数MyClass<Type>(const MyClass<OtherType>& x)并调用MyClass<Type>::test<Type>(const MyClass<Type>& x) .

情况 2:推导的参数是优先级:调用MyClass<Type>::test<Type>(const MyClass<OtherType>& x)


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


编辑:测试函数由以下调用:

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

test将被称为

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

即不会将uiMyClass<unsigned int>MyClass<double>

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

来自 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) }

— 结束示例 ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM