templates - type as returntype in c++ -
is there possibility return type returntype function , use member variable using this:
constexpr type myfunction(int a, int b){ if(a + b == 8) return int_8t; if(a + b == 16) return int_16t; if(a + b == 32) return int_32t; return int_64t; } template<int x, int y> class test{ using type = typename myfunction(x, y); private: type m_variable; };
when trying example in qt says
error: 'constexpr' not name type error: 'test' not template type class test{ ^
in earlier question showed me http://en.cppreference.com/w/cpp/types/conditional function, works 2 types.
you cannot normal function. however, done using template meta-programming. kind of template called type function.
#include <cstdint> template<int bits> struct integer { /* empty */ }; // specialize bit widths want. template<> struct integer<8> { typedef int8_t type; }; template<> struct integer<16> { typedef int16_t type; }; template<> struct integer<32> { typedef int32_t type; };
it can used this.
using integer_type = integer<16>::type; integer_type number = 42;
remember precede integer<t>::type
typename
keyword if t
template parameter.
i leave exercise extend template accepts 2 integers parameters , returns appropriate type based on sum of two.
Comments
Post a Comment