I'm trying to create a function which return type should depend on switch statement, something like:
auto function_name (int value) {
switch (value) {
case 1 : {return 2.3;}
case 2 : {return 1;}
case 3 : {return "string";}
}
}
But I can't because of an error:
error: inconsistent deduction for auto return type: 'double' and then 'int'
What can I do to create something similar by functionality to the example above?
A function in C++ can only have a single type that it returns. If you use auto
as the return type and you have different return statements that return different types then the code is ill-formed as it violates the single type rule.
This where std::variant
or std::any
needs to be used. If you have a few different types that could be returned via some run-time value then you could use either of those types as "generic type". std::variant
is more restrictive as you have to specify the types it could be, but it also less expensive then std::any
because you know what types it could be.
std::variant<double, int, std::string> function_name (int value) {
using namespace std::literals::string_literals;
switch (value) {
case 1 : {return 2.3;}
case 2 : {return 1;}
case 3 : {return "string"s;} // use ""s here to force it to be a std::string
}
}
Will let you return different types.