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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With