c++ - 使用 enable_if 禁用模板类的模板构造函数

标签 c++ c++11 templates variadic-templates sfinae

当模板构造函数的参数类型与类型“MyClass 匹配时,我试图使用 std::enable_if 禁用模板类的模板构造函数"这样我就可以使用我的其他构造函数,它允许我用另一个模板的类初始化当前模板的类。

template <typename t, size_t size>
class MyClass
{
public: 
   MyClass() { data.fill(static_cast<T>(0)); }

   template <typename... Args> // i want to disable this if Args = MyClass
   MyClass(Args&&... args) : data{ std::forward<Args>(args)... } {}

   template <size_t size2>
   MyClass(const Myclass<t, size2>& other_sized_template) { /*do stuff*/ } // this won't work unless the template ctor above is disabled if the arguments passed are of type Myclass

private:
   std::array<t, size> data;
};

最佳答案

您可以通过部分特化的类模板检查该类型是否是 MyClass 的实例化。例如

template<class...>
struct is_MyClass : std::false_type {};

template <typename T, size_t size>
struct is_MyClass<MyClass<T, size>> : std::true_type {};

然后像这样禁用构造函数

template <typename... Args, 
          typename = std::enable_if_t<
            !is_MyClass<
              std::remove_cv_t<
                std::remove_reference_t<Args>>...>::value> > // i want to disable this if Args = MyClass
MyClass(Args&&... args) : data{ std::forward<Args>(args)... } {}

LIVE

关于c++ - 使用 enable_if 禁用模板类的模板构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46840595/

相关文章:

c++ - 基于C++11的线程类库

c++ - CUDA NSight c++11 (Ubuntu 14.04)

c++ - 为什么调用 boost::split() 会给出这么多警告?

c++ - 使用指针时访问冲突写入位置

c++ - 类映射对象的成员函数

c++ - 当仅提供一些模板参数时,C++编译器如何推断模板参数

c++ - 可变参数模板 : Interlacing multiple packs

c++ - 模板特化函数 C++

模板类中的 C++ 非模板方法

c++ - 对于在类外定义的友元函数,模板上的隐式转换查找失败