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 的模板.
目标是使用Y
为 A
呈现一个漂亮的界面, 允许写类似 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/