2012-08-24 16 views
17

Rozważmy następujący kod:Dodawanie/usuwanie elementów danych z parametrami szablonu?

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

    protected: 
     double myVariable; 
     /* SOMETHING */ addedVariable; 
}; 

W tym kodzie parametr szablonu AddMembers pozwolić aby dodać funkcję do klasy, kiedy to true. Aby to zrobić, używamy std::enable_if.

Moje pytanie brzmi: czy to samo możliwe (może z podstępem) dla zmiennej członków danych? (W taki sposób, że MyClass<false> będzie mieć element 1 danych (myVariable) i MyClass<true> posiadają 2 użytkowników danych (myVariable i addedVariable)

Odpowiedz

21

Warunkowe klasy zasadę można stosować:

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

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

pierwsze, .. Twój kod po prostu nie będzie kompilować na MyClass<false>enable_if cecha jest przydatna dla wyprowadzona argumentów, a nie argumentów klasa szablonu

drugie, oto jak można kontrolować członków:

template <bool> struct Members { }; 

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

template <bool B> struct Foo : Members<B> 
{ 
    double y; 
}; 
+0

+++++ 1 idealny! Mixin z warunkowym parametrem szablonu – Viet