c++ - Initialize base subobject with dependent type name in derived class -
c++ - Initialize base subobject with dependent type name in derived class -
given sample code class c
deriving a
or b
depending on policy
#include <iostream> #include <type_traits> struct { a(int a) { std::cout << << "\n"; } }; struct b { b(int a) { std::cout << -a << "\n"; } }; template<bool> struct policy; template<> struct policy<true> { typedef type; }; template<> struct policy<false> { typedef b type; }; template<typename t> struct c : public policy<std::is_polymorphic<t>::value>::type { c() : /* ????? */(5) {} }; int main() { c<int> a; // should print -5 c<std::ostream> b; // should print 5 }
how initialize base of operations class of c
? (or, if it's not possible, there workaround?)
do way found base of operations class of c
:
template<typename t> struct c : public policy<std::is_polymorphic<t>::value>::type { c() : policy<std::is_polymorphic<t>::value>::type(5) {} };
of course, create more readable, can add together typedef (maybe need base of operations class multiple times within c
, it's worth it). this:
template<typename t> struct c : public policy<std::is_polymorphic<t>::value>::type { typedef typename policy<std::is_polymorphic<t>::value>::type base; c() : base(5) {} };
to create little less ugly, add together layer of indirection, e.g. template class baseforc
yields right base of operations baseforc<t>::type
, encapsulates policy
, is_polymorphic
doing 1 class.
c++ c++11 typetraits
Comments
Post a Comment