Reputation: 1926
I'm trying to write a function that returns various types depending on the if-statement.
auto parseParameterValue(QString aParameterValueString, int aParameterType)
{
if(aParameterType == 0)
{
int result = aParameterValueString.toInt();
return result;
}
else if(aParameterType == 1)
{
double result = aParameterValueString.toDouble();
return result; // <------- compilation error
}
else
{
return aParameterValueString;
}
}
Unfortunately what I get is:
- Warning: 'parseParameterValue' function uses 'auto' type specifier without trailing return type
- Error at second return: inconsistent deduction for 'auto': 'int' and then 'double'
Is there a way to make it work?
Thanks in advance.
Upvotes: 3
Views: 2136
Reputation: 45464
You could return an erasure type, such as boost::any
, which can store any type. Your code would then look like this
boost::any parseParameterValue(QString aParameterValueString, int aParameterType)
{
switch(aParameterType) {
default: return {aParameterValueString};
case 0: return {aParameterValueString.toInt()};
case 1: return {aParameterValueString.toDouble()};
}
}
Upvotes: 4
Reputation: 72431
No, a function can only have one return type.
Note that processing of a function return type must happen at compile time, but your function uses values that can't be known until run time.
Upvotes: 10