Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a type depending on the parameter

I want to have such a function that it's return type will be decided within the function(depending on the value of the parameter), but failed implementing it. (template specialization maybe?)

// 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 the type as:

auto val = GetVar(42); // val's type is std::string
like image 504
Ausser Avatar asked Nov 09 '22 14:11

Ausser


1 Answers

That does not work, you would have to give the parameter at compile time. The following would work:

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 version would be to pass std::integral_constant, like this:

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
like image 84
Klemens Morgenstern Avatar answered Nov 15 '22 06:11

Klemens Morgenstern