C ++,我可以禁止特定的策略组合吗?

时间:2012-10-13 00:47:06

标签: c++ templates typetraits

给定一个带有两个策略模板参数的类:

template<typename PolicyA, typename PolicyB>
class widget;

以下可用的政策等级A1,A2,A3,B1,B2,B3。如何传达1和2彼此兼容,但A3只与B3兼容?也就是说,只允许以下实例化:

widget<A1, B1> w11;    // All valid.
widget<A1, B2> w12;
widget<A2, B1> w21;
widget<A2, B2> w22;
widget<A3, B3> w33;

// No other combination allowed.

我在专门化中使用std :: enable_if失败的尝试遇到了编译错误:

template<typename A, typename B>
class<A3, enable_if<is_same<B, B3>::value, B3>::type>
{};

3 个答案:

答案 0 :(得分:1)

class A1; class A2; class A3; class B1; class B2; class B3;

/// Generic type
template <typename T1, typename T2>
class widget
{
  static_assert(std::is_same<T1, A3>::value ^ !std::is_same<T2, B3>::value,
    "Incompatible policy types selected.");
};

/// Some specialization
template <>
class widget<A1, A2>
{
};

widget<A1, B1> w11;
widget<A1, B2> w12;
widget<A2, B1> w21;
widget<A2, B2> w22;
widget<A3, B3> w33;
//widget<A1, B3> w13; // error C2338: Incompatible policy types selected.
//widget<A3, B2> w32; // error C2338: Incompatible policy types selected.

答案 1 :(得分:0)

听起来你已经了解specialized templates

无论如何,一个想法是为不兼容的类型定义一个专门的模板,自动抛出IncompatibleException或其他东西。

从技术上讲,用户可以定义类型,但它将无法使用且完全明显。

答案 2 :(得分:0)

简单的解决方案是对每个不兼容的情况进行专门化,并使其包含会触发编译错误的内容。像这样:

template <>
class widget<A1, B3> {
  char error__policies_A1_and_B3_are_incompatible[0];
};

长度为0的char数组将关闭编译器,并且“message”将出现在编译错误的某处。