Enter return type in C ++
Is it possible to return a type as a return type from a function and use it for a member variable using something like 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 this example in Qt, it says
Error: 'constexpr' does not name a type
Error: 'test' is not a template type
class test{
^
In an earlier question, someone showed me http://en.cppreference.com/w/cpp/types/conditional this feature, but it only works for 2 types.
source to share
You cannot do this with a normal function. However, this is easily done using template meta-programming. This type of template is sometimes called a type function.
#include <cstdint>
template<int bits> struct integer { /* empty */ };
// Specialize for the bit widths we 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 be used as follows.
using integer_type = integer<16>::type;
integer_type number = 42;
Don't forget to prefix integer<T>::type
with the keyword typename
if T
itself is a template parameter.
I leave this as an exercise for you to extend to a template that takes two integers as parameters and returns the appropriate type based on the sum of the two.
source to share