可以使用C ++策略类来指定构造函数的存在/不存在吗?

时间:2010-02-26 22:29:43

标签: c++ templates policy

假设我有:

struct Magic {
  Magic(Foo* foo);
  Magic(Bar* bar);
};

有没有办法让Magic成为模板,并定义模板类s.t。

typedef Magic<FooPolicy, ...> MagicFoo;
typedef Magic<BarPolicy, ...> MagicBar;
typedef Magic<..., ...> MagicNone;
typedef Magic<FooPolicy, BarPolicy> MagicAll;

s.t。 MagicFoo&amp; MagicAll有Foo *构造函数; MagicBar&amp; MagicAll有Bar *构造函数;和MagicNone既不是Foo *也不是Bar *构造函数?

基本上我希望构造函数基于策略类存在或不存在。

3 个答案:

答案 0 :(得分:4)

您可以编写一个接受任何内容的构造函数,然后委托给策略提供的任何内容:

// "Tag" and "No" are used to make the class/function unique 
// (makes the using declarations work with GCC). 
template<int Tag>
struct No { void init(No); };

template<typename P1 = No<0>, typename P2 = No<1>, typename P3 = No<2> >
struct Magic : P1, P2, P3 {
  template<typename T>
  Magic(T t) {
    init(t);
  }

private:
  using P1::init;
  using P2::init;
  using P3::init;
};

现在,一旦转发参数,编译器将找出策略中的最佳匹配:

struct IntPolicy { void init(int) { std::cout << "called int!"; } };
struct FloatPolicy { void init(float) { std::cout << "called float!"; } };
Magic<IntPolicy, FloatPolicy> m(0), n(0.0f);

答案 1 :(得分:0)

这看起来像是子类的应用程序,而不是策略类。 MagicFooMagicBar似乎想成为Magic的子类,protected本身可能有{{1}}个构造函数。

答案 2 :(得分:-1)

您可以为所有政策制定模板定义,并为MagicNone提供专业化。一个例子是:

template<class T> 
 struct Magic {
  Magic(T *o) {}
};

struct None {};

// specialize for MagicNone
template<> struct Magic<None> {
  Magic() {} // default ctor
};

int main()
{
  int a = 32;
  Magic<int> mi(&a);
  Magic<None> m;
}