除非另有说明,否则如何强制模板 class 使用指定的类型?
How to force template class to use specified type unless specified otherwise?
我的模板有问题 class。我像这样指定了我的模板的默认类型 class:
template < class T = float >
class apple {
public:
T x;
apple(T x): x(x) {}
}
但是,当我这样创建对象时:
apple obj(2);
类型变成 int 除非我这样做:
apple<float> obj(2);
如何让它保持浮动?
像
一样使用默认模板参数的特化
apple<> obj( 2 );
添加此推导指南以强制所有参数推导解析为您的默认参数:
template <class T>
apple(T) -> apple<>;
另一种可能的解决方案是修改构造函数:
apple(std::enable_if_t<1, T> x): x(x) {}
这样编译器将无法从您传递给 x
的参数中推断出 T
,并将使用 T
(您提供的)的默认类型相反。
我的模板有问题 class。我像这样指定了我的模板的默认类型 class:
template < class T = float >
class apple {
public:
T x;
apple(T x): x(x) {}
}
但是,当我这样创建对象时:
apple obj(2);
类型变成 int 除非我这样做:
apple<float> obj(2);
如何让它保持浮动?
像
一样使用默认模板参数的特化apple<> obj( 2 );
添加此推导指南以强制所有参数推导解析为您的默认参数:
template <class T>
apple(T) -> apple<>;
另一种可能的解决方案是修改构造函数:
apple(std::enable_if_t<1, T> x): x(x) {}
这样编译器将无法从您传递给 x
的参数中推断出 T
,并将使用 T
(您提供的)的默认类型相反。