【发布时间】:2015-10-22 13:22:08
【问题描述】:
我正在尝试编写一个模板函数,该函数将根据传入的字符串返回不同的类型。
template<typename T>
T test(string type)
{
int integer = 42;
float floateger = 42.42;
if (type == "int")
return integer;
if (type == "float")
return floateger;
}
int main()
{
int integer = test("int");
cout << "INTEGER: " << integer << endl;
}
当我运行它时,我收到以下错误:
错误:没有匹配的函数调用 'test(const char [4])
我怎样才能实现这样的事情?
我的最终目标是编写一个函数,该函数将根据传入的字符串返回不同类的对象。我知道这可能根本不是正确的方法。这样做的正确方法是什么?
【问题讨论】:
-
考虑
boost::any -
看起来你需要多态性
-
当您意识到这可能不是正确的方法时,您可能应该详细说明您实际尝试做的事情 - 而不是专注于解决问题的方法(以及如何做到这一点)?
-
不要那样做。你不能。
-
@NeilKirk 先爬再跑。