简体   繁体   English

如何隐式转换模板化的构造函数参数?

[英]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.

相关问题 C ++如何隐式地将参数转换为比较器,如&lt;? - How does C++ implicitly cast arguments to a comparator such as <? 如何将模板 function 的所有 arguments 隐式转换为最高分辨率类型? - How to implicitly cast all arguments of a template function to the highest resolution type? 模板化构造函数中的模板参数数 - Number of template arguments in templated constructor 如何创建一个带有可变数量参数的模板化函数,该参数将参数传递给对象的正确构造函数? - How to create a templated function taking a variable number of arguments that passes the arguments to an object's correct constructor? 可变参数模板构造函数不接受x参数 - Variadic templated constructor does not take x arguments 如何构造一个std :: variant类型的对象,其本身是Templated和构造函数转发参数 - How to Construct an std::variant type object whose itself Templated and constructor forwards arguments 如何专门化模板化构造函数? - How to specialize a template constructor templated? 如何获得两个可以隐式转换为彼此的模板化类 - How to get two templated classes implicitly convertible to one another 我如何投射模板类 - How do I cast a templated class 递归模板 arguments:调用隐式删除的默认构造函数 C++ - Recursive templates arguments: call to implicitly deleted default constructor C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM