Henry
Henry

Reputation: 53

C++ function returning different types

I was trying to make a function where based on the parameter the function returns the value, like this:

type getValue(string input) return <OUTPUT>

OUTPUT's type would be changed to int, string, bool, etc., on what the input is given. I got that sorted but the problem that I've been having is the return type. I've tried auto type but all I got was this error:

error: inconsistent deduction for 'auto': 'int' and then 'char'

over and over again with every single types that this function can output. I wouldn't do templates because you have to do this

getValue<type>(input);

and I have no way to just guessing to output to put in the template type. I've used so many options that I can do but it was just way too complicated.

Upvotes: 3

Views: 441

Answers (1)

mattlangford
mattlangford

Reputation: 1260

As the comments point out, you'll need to use a std::variant or std::any as a return type.

std::any getValue(string input) {
    if (input == ...) {
        return "string return type";
    }
    if (input == ...) {
        return 100;
    }
    if (input == ...) {
        return 123.456;
    }

    return false;
}

However if there are only a small set of return types you could produce, consider using a variant as it's a bit more constrained:

// assuming these are the only 4 types you can return
using getValueReturnType = std::variant<std::string, int, double, bool>;

// The function definition would be exactly the same as above with std::any
getValueReturnType getValue(string input);

Upvotes: 1

Related Questions