Can C ++ policy classes indicate the existence / absence of constructors?

Suppose I have:

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

Is there a way to make Magic a template and define st template classes

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

st MagicFoo and MagicAll have a constructor Foo *; MagicBar and MagicAll have a constructor Bar *; and MagicNone is neither a constructor of Foo * nor Bar *?

Basically, I want constructors to exist or not to exist based on policy classes.

+3
source share
3 answers

You can write a constructor that accepts anything, and then delegate everything the policy provides:

// "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;
};

Now, as soon as you move the argument, the compiler will determine the best match between the policies:

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);
+4

, . MagicFoo MagicBar, , Magic, protected.

0

You may have a template definition for all policies and a specialization for MagicNone. An example is:

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;
}
-1
source

Source: https://habr.com/ru/post/1734622/


All Articles