Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function that conditionally returns different types

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?

like image 435
tjwrona1992 Avatar asked May 30 '26 18:05

tjwrona1992


1 Answers

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;
}
like image 171
molbdnilo Avatar answered Jun 02 '26 07:06

molbdnilo