我想要一个这样的函数,它的返回类型将在函数内决定(取决于value参数),但未能实现它。 (也许模板专业化?)
// 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)