"TypeTrait" static / extern
-
Hallo,
ich breche mein Problem mal bis aufs nötigste herunter. Ich habe folgende (Beispiel-)Klassen:
template<bool b> struct TypeTrait { static int x; }; template<> int TypeTrait<true>::x; template<> struct TypeTrait<false> { int x; } template<bool b> class MyClass : private TypeTrait<b> { /*static*/ void foo(int y) { x += y; cout << x << endl; } };void MyClass::foo(int) soll im Falle das "b" "true" ist, static sein.
Ich suche nach einer eleganten Art dies zu lösen; ohne Spezialisierung und den identischen (!) Body neuschreiben zu müssen.Hat da jemand eine elegantere Lösung?
-
Ohne Spezialisierung wird es schwer. Das Neuschreiben kann man sich über eine zusätzliche Indirektion sparen:
void foo_impl(int & x, int y) { x += y; std::cout << x << '\n'; } template<bool b> struct TypeTrait //eigentlich eher ein Verhalten { static void foo(int y) { foo_impl(x, y); } static int x; }; template<bool b> int TypeTrait<b>::x; template<> struct TypeTrait<false> { void foo(int y) { foo_impl(x, y); } int x; }; template<bool b> class MyClass : private TypeTrait<b> { public: using TypeTrait<b>::foo; };