[英]How to implicitly cast templated constructor arguments?
I'm overloading the constructor of a templated class A
with different input types, for both scalar and container-type arguments: 我正在使用不同的输入类型重载模板化类A
的构造函数,包括标量和容器类型参数:
template<typename T>
class A {
public:
A();
A(T&& _val) { printf("non-template constructor\n");} ;
template<typename iT> A(const iT& _cont) { printf("template constructor\n");};
};
int main(int argc, char const *argv[]) {
A<float> foo1(0.9); //template constructor
A<float> foo2((float)0.9); //no-template constructor
A<float> foo3(std::vector<int>(5,8)); //template constructor
return 0;
}
However, is there a way to call force the non-template constructor on implicitly castable types eg passing a double
to constructor A<float>()
? 但是,有没有办法在隐式可转换类型上调用非模板构造函数,例如将double
传递给构造函数A<float>()
?
Yes, you can add a SFINAE-constraint to your constructor template: 是的,您可以在构造函数模板中添加SFINAE约束:
template<typename iT,
std::enable_if_t<!std::is_convertible_v<iT&&, T>>* = nullptr>
A(const iT&) { printf("template constructor\n"); }
This has the effect of causing substitution failure for the deduced type iT
when iT&&
is convertible to T
, which removes the constructor template from the overload set. 当iT&&
可转换为T
,这会导致推导类型iT
替换失败,从而从重载集中删除构造函数模板。
(You need to #include <type_traits>
for the various library facilities used to express the constraint.) (对于用于表示约束的各种库工具,您需要#include <type_traits>
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.