i write class have 2 template parameter both of them boolean. both of them can enable different functionalities if set true. acheave (this not working):
template<bool a, bool b> class foo { private: int v1; #if int v2; #endif public: void f1() {} #if b void f2() {} #endif int f3() { #if return v2; #else return v1; #endif } } how can achieve goal without perforamnce penalty?
crtp, specialization, , refactoring:
template<typename d, bool a> struct foo_a { public: d const* self() const { static_assert( std::is_base_of<foo_a<d,a>, d>::value, "crtp failure" ); return static_cast<d const*>(this); } d* self() { static_assert( std::is_base_of<foo_a<d,a>, d>::value, "crtp failure" ); return static_cast<d*>(this); } void f3() { return self()->v2; } }; template<typename d> struct foo_a<d, true> { private: int v2; public: d const* self() const { static_assert( std::is_base_of<foo_a<d,a>, d>::value, "crtp failure" ); return static_cast<d const*>(this); } d* self() { static_assert( std::is_base_of<foo_a<d,a>, d>::value, "crtp failure" ); return static_cast<d*>(this); } void f3() { return self()->v1; } }; template<typename d, bool b> struct foo_b {}; template<typename d> struct foo_b<d,true> { void f2() {} }; template<bool a, bool b> class foo: foo_a<foo<a,b>,a>, foo_b<foo<a,b>,b> { private: int v1; public: void f1() {} }; crtp lets helper classes have static compile time access contents of class, , other helper classes.
specialization in helper classes, proper refactoring, gives nice tight conditions aren't growing exponentially. can common logic in derived class, , access these values in each specialization.
Comments
Post a Comment