如何隐式转换模板化构造函数参数? [英] How to implicitly cast templated constructor arguments?
问题描述
对于标量和容器类型参数,我正在用不同的输入类型重载模板类 A
的构造函数:
I'm overloading the constructor of a templated class A
with different input types, for both scalar and container-type arguments:
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;
}
但是,有一种方法可以隐式地强制强制非模板构造函数铸造类型,例如将 double
传递给构造函数 A< float>()
?
However, is there a way to call force the non-template constructor on implicitly castable types e.g. passing a double
to constructor A<float>()
?
推荐答案
是的,您可以向构造函数模板添加SFINAE约束:
Yes, you can add a SFINAE-constraint to your constructor template:
template<typename iT,
std::enable_if_t<!std::is_convertible_v<iT&&, T>>* = nullptr>
A(const iT&) { printf("template constructor\n"); }
这会导致推导类型 iT <的替换失败。 / code>当
iT&
可转换为 T
时,这将使构造函数模板从重载中删除
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.
(您需要 #include< type_traits>
来表示约束的各种库工具)
(You need to #include <type_traits>
for the various library facilities used to express the constraint.)
这篇关于如何隐式转换模板化构造函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!