¿Agregar/eliminar miembros de datos con parámetros de plantilla?

Considere el siguiente código:

template<bool AddMembers> class MyClass
        void myFunction();
        template<class = typename std::enable_if<AddMembers>::type> void addedFunction();

        double myVariable;
        /* SOMETHING */ addedVariable;

In this code, the template parameter AddMembers allow to add a function to the class when it's true. To do that, we use an std::enable_if.

My question is : is the same possible (maybe with a trick) for data members variable ? (in a such way that MyClass<false> will have 1 data member (myVariable) y MyClass<true> will have 2 data members (myVariable y addedVariable)?

preguntado el 25 de agosto de 12 a las 00:08

2 Respuestas

A conditional base class may be used:

struct BaseWithVariable    { int addedVariable; };
struct BaseWithoutVariable { };

template <bool AddMembers> class MyClass
    : std::conditional<AddMembers, BaseWithVariable, BaseWithoutVariable>::type
    // etc.

Respondido 25 ago 12, 00:08

First off, your code just won't compile for MyClass<false>. enable_if trait is useful for deducido arguments, not for class template arguments.

Second, here's how you could control members:

template <bool> struct Members { };

template <> struct Members<true> { int x; };

template <bool B> struct Foo : Members<B>
    double y;

Respondido 25 ago 12, 00:08

+++++1 perfect! Mixin with conditional template parameter - Viet

I found this better than the accepted answer, thanks! - mojo1mojo2

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.