Return type depending on parameter

I want to have a function such that the type of the return value is determined inside the function (depending on the value ), but did not implement it. (perhaps specialization of the template?)

// half-pseudo code
auto GetVar(int typeCode)
{
  if(typeCode == 0)return int(0);
  else if(typeCode == 1)return double(0);
  else return std::string("string");
}

And I want to use it without specifying a type like:

auto val = GetVar(42); // val type is std::string
+4
source share
3 answers

This does not work, you will need to specify the parameter at compile time. The following would be done:

template<int Value>
double GetVar() {return 0.0;};

template<>
int GetVar<42>() {return 42;}

auto x = GetVar<0>(); //type(x) == double
auto y = GetVar<42>(); //type(x) == int

Another option is to pass std :: integral_constant, for example:

template<int Value>
using v = std::integral_constant<int, Value>;

template<typename T>
double GetVar(T) {return 0;};

int GetVar(v<42>) {return 42;};

auto x = GetVar(v<0>()); //type(x) == double
auto y = GetVar(v<42>()); //type(x) == int
+1
source

++ -, , , .
void *.

0
#include <type_traits>
#include <iostream>

// foo1 overloads are enabled via the return type
template<class T>
typename std::enable_if<std::is_floating_point<T>::value, T>::type 
foo1(T t) 
{
    std::cout << "foo1: float\n";
    return t;
}
0
source

All Articles