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

Joh*_*yne 5 c++ templates sfinae variadic-templates c++11

我正在尝试使用模板构造函数std::enable_if的参数类型匹配类型" MyClass" 时禁用模板类的模板构造函数,以便我可以使用我的其他构造函数,这允许我使用类初始化当前模板的类另一个

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;
};
Run Code Online (Sandbox Code Playgroud)

son*_*yao 5

You can check whether the type is an instantiation of MyClass by a class template with partial specialization. e.g.

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

template <typename T, size_t size>
struct is_MyClass<MyClass<T, size>> : std::true_type {};
Run Code Online (Sandbox Code Playgroud)

then disable the constructor like

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)... } {}
Run Code Online (Sandbox Code Playgroud)

LIVE