I'm attempting to write a template function that will return different types based on a string that is passed in.
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;
}
When I run this I get the following error:
error: no matching function for call to 'test(const char [4])
How can I implement such a thing?
My end goal is to write a function that will return objects of different classes depending on what string is passed into it. I know this probably isn't the right approach at all. What is the correct way to do something like this?
A function always returns a value of the same type.
What you can do is to return a pointer to a common base class:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With