tjw*_*992 3 c++ templates function
我正在尝试编写一个模板函数,该函数将根据传入的字符串返回不同的类型。
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;
}
Run Code Online (Sandbox Code Playgroud)
当我运行这个时,我收到以下错误:
错误:没有匹配的函数可用于调用“test(const char [4])”
我怎样才能实现这样的事情呢?
我的最终目标是编写一个函数,该函数将根据传递给它的字符串返回不同类的对象。我知道这可能根本不是正确的方法。做这样的事情的正确方法是什么?
函数总是返回相同类型的值。
您可以做的是返回一个指向公共基类的指针:
struct A {};
struct B : A {};
struct C : A {};
A* make(const std::string& s)
{
if (s == "B")
return new B;
else if (s == "C")
return new C;
else
return nullptr;
}
Run Code Online (Sandbox Code Playgroud)