我想要这样一个函数,它的返回类型将在函数内决定(取决于参数的值),但未能实现。 (可能是模板特化?)
// 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");
}
我想在不指定类型的情况下使用它:
auto val = GetVar(42); // val's type is std::string
最佳答案
那不行,你必须在编译时给出参数。以下将起作用:
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
另一个版本是传递 std::integral_constant,像这样:
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
关于c++ - 根据参数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30088983/