将 enable_if 与两个级别的模板一起使用

Use enable_if with two levels of templating

我想使用 enable_if 为某些类型定义 class。在这些类型中,我需要使用一些模板化类型,但我无法使其工作。这是一个 MWE:

模板化classA:

template<typename T, typename Enable = void> class A;

它对一些简单类型的特化,比如这里的整数类型,可以定义如下:

template<typename T>
class A<T, std::enable_if<std::is_integral<T>::value>::type>
{ ... };

现在我定义了一堆模板化类型:

template<typename U> class X {...};
template<typename U> class Y {...};

我应该如何继续将我的 class A 专门化为类型 XY

两次尝试均无效:

  1. 对于以下内容,声明类型为 A<X<int> > 的对象会产生错误 incomplete type:

    template<typename U>
    template<typename T>
    class A<T, std::enable<std::is_same<T, X<U> >::value 
                        || std::is_same<T, Y<U> >::value>::type> 
    { ... };
    
  2. 加上下面的错误是'T' is not a template.

    template<typename U>
    template<typename T>
    class A<T<U>, std::enable<std::is_same<T, X>::value 
                           || std::is_same<T, Y>::value>::type>
    { ... };
    

XYclass 模板 ,不是类型。您的编译器正确地抱怨在您的第二个示例中使用类型作为 class 模板。

如果您想为他们进行专业化

template<typename>
class A;

template<typename T>
class A<X<T>> : A_for_XY<X<T>> {};

template<typename T>
class A<Y<T>> : A_for_XY<Y<T>> {};