template <typename X, typename Y> class A {
    // Use Y::Q, a useful property, not used for specialization.
};
enum Property {P1,P2};
template <Property P> class B {};
class C {};

有什么方法可以定义 A 的部分特化,使 A<C, B<P1> > 成为 A 的普通模板,但 A<C, B<P2> > 将成为特化?

针对 Marcelo 进行编辑:更具体地说,不应仅针对 B 选择特化,还应针对表现出特定属性的任何类型(例如,它是第一个参数为 P2 的模板)选择特化。

目标是使用 YA 提供一个漂亮的界面,允许编写类似 A<C, Y<P2,Q> > 的东西。

用模板模板参数替换 Y 模板参数会很好,但是有没有办法基于 P 部分地专门化它呢?

目的是编写如下内容:
template <typename X, template <Property P> typename Y> class A {};
template <typename X> class A<X,template<> Y<P2> > {}; // <-- not valid

针对 In silico 进行编辑:我说让 Y 成为模板模板参数会很好,但实际上这违背了我想要做的目的,即使用 Y 将逻辑链接的属性组合在一起,但仍然专门化 A基于这些子属性之一。

有没有办法将特征添加到特化 template <> class B<P2> ,然后在 A 中使用 SFINAE ?目的是编写如下内容:
template <> class B<P2> {
    typedef int IAmP2;
};

// The following is not valid because it's a simple redefinition.
template <typename X, typename Y> class A {
    // Substitution using this template would fail for Y<P1>, and only the
    // general template would be left for selection.
    typename Y::IAmP2 skipIfNotP2;
};

最佳答案

我不明白你的意思。模板模板参数似乎是解决方案,尽管您不知何故说它们不起作用。为什么不这样做?

template <typename X, typename Y>
class A {
};

template <typename X, template<typename> class Y, typename P>
class A< X, Y<P> > {
  /* property is P */
};

对于您的 SFINAE 问题,是的,这也是可能的
template <typename X, typename Y, typename Sfinae = void>
class A {
};

template <typename X, typename Y>
class A< X, Y, typename Y::IAmP2 > {
  /* Y is the class having a property */
};

class Sample {
  typedef void IAmP2;
};

我仍然不确定你的意思。

关于c++ - 部分模板特化 : matching on properties of specialized template parameter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2934042/

10-11 22:55
查看更多