c++ - C++11: conditional compilation: members -
i'm trying make struct conditional members, means, different members exists specific specializations. but, want classes fastest possible. i've tried in 3 differents ways:
way 1:
template<typename t, bool with_int = false> struct foo { template<typename... args> foo(args&&... args) : m_t(forward<args>(args)...) {} t m_t; } template<typename t> struct foo<t, true> { template<typename... args> foo(args&&... args) : m_t(forward<args>(args)...), m_id(0) {} t m_t; int m_id; };
- disadventage: repeated code each specialization.
way 2:
template<typename t, bool with_int = false> struct foo { template<typename... args> foo(args&&... args) : m_t(forward<args>(args)...) {} virtual ~foo() {} t m_t; } template<typename t> struct foo<t, false> : public foo<t> { using foo<t>::foo; int m_id = 0; };
- adventage: few code.
- disadventage: use of vtables/inheritance/etc: more time in construction or access members? but, in other way, don't pretend to use "references" base class. real adventages or disadventages of aproach?
way 3
using nil_type = void*; using zero_type = nil_type[0]; template<typename t, bool with_int = false> struct foo { template<typename... args, typename = typename enable_if<with_int>::type> foo(args&&... args) : m_t(forward<args>(args)...), m_int(0) {} template<typename... args, typename = typename enable_if<!with_int>::type> foo(args&&... args) : m_t(forward<args>(args)...) {} t m__t; typename conditional<with_int, int, zero_type>::type m_int; };
- ventages: write code once; when
with_int
false
, fieldm_int
has size 0 (almost gcc 4.7.2). - adventages: more use of templates (reduce readability) , i'm not sure how compilers deal member of size 0. don't know indeed extent size-0-field dangerous or has sense. repeated constructors, perhaps avoidable.
what best approach or method?
have considered inheritance?
template< bool > struct foo_int_base { // stuff without int void f(); // not use m_id }; template<> struct foo_int_base< true > { // stuff int int m_id = 0; void f(); // uses m_id }; template< typename t, bool with_int = false > struct foo : foo_int_base< with_int > { // common stuff here };
Comments
Post a Comment