1

I would like to exclude or include some members in a template class, based on the value of its template parameter. Here's an example:

enum t_chooser {A, B, all};

template <t_chooser choice>
class C {

    // include if choice==A
    int v1;
    // include if choice==B
    long v2;
    // include if choice==B    
    int v3;
    // include for every value of choice
    bool v4;
};

If the template parameter choice is equal to all, all members should be included. Is there a way to achieve this in C++11, maybe even using std::enable_if?

I have seen a solution for member functions here: std::enable_if to conditionally compile a member function

Community
  • 1
  • 1
Endre
  • 690
  • 8
  • 15
  • It would also be interesting to know, if it is possible to include / exclude lines of code in methods, where these variable are used, i.e. writing a method that works for all template values, similarly to an `#ifdef` macro. – Endre Jul 24 '15 at 22:40
  • you can TMP most things like this but you'll need helpers. – Ryan Haining Jul 25 '15 at 00:37

1 Answers1

4

Obviously you could specialize the entire C class for each type of t_chooser but that's a pain since you'd have to duplicate everything. Instead you can put the specialization into a helper struct and then derive it in C

enum t_chooser {A, B, all};

template <t_chooser choice>
struct Vars; // undefined

template<>
struct Vars<A> { // just the A vars
  int v1;
};

template<>
struct Vars<B> { // just the B vars
  long v2;
  int v3;
};

template<>
struct Vars<all> : Vars<A>, Vars<B> { }; // derive both, get everything

template <t_chooser choice>
class C : private Vars<choice> { // or public if you want to expose them
    bool v4;
};
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174