默认值与推导模板参数
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:默认参数为 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> &)
即不会将ui
从MyClass<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) }
— 结束示例 ]
相关文章:
- 当给定默认值时,为什么此模板参数推导失败
- 如何在C++中提供模板化函数作为另一个函数的参数,默认值?
- 在 c++ 中,如果我创建一个接受一个具有默认值的参数的构造函数 - 它会用作默认(空)构造函数吗?
- 为什么无法在可变参数模板中将尾随模板参数指定为默认值?
- 可变参数模板和具有继承的默认值
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 在子类函数覆盖中省略具有默认值的参数
- 函数作为具有默认值的参数
- 具有另一个具有默认值的模板参数的模板推导
- const变量是否可以在具有默认值的参数中赋值(作为可选参数)
- 可以通过常量引用返回默认参数的值吗?
- 对 const 引用参数使用默认值会导致崩溃
- C ,构造器中允许的参考参数默认值
- 是否可以设计一个包含模板参数默认值的类
- 构造函数中参数C++默认值
- 如何设置依赖于其他参数的参数默认值
- QInput对话框参数默认值
- 在函数定义中指定参数默认值会导致错误 C2143:语法错误:'='之前缺少')'
- 内置类型的模板参数默认值
- 是否可以使用构造函数或对象作为其他类方法的参数默认值?