默认值与推导模板参数

Default vs Deduced template parameter?

本文关键字:参数 默认值      更新时间:2023-10-16

在下面:

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

— 结束示例 ]