我希望实现一个这样的函数,其返回类型将取决于函数内部传入参数的值,但我无法成功实现它。(也许可以使用模板特化实现?)
// 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
boost::variant
。 - chrisauto
的类型是在编译期间推导出来的,而不是在运行时确定的。 - molbdnilotypeCode
是在编译时已知的还是在运行时确定的? - Nasser Al-Shawwa