C ++ function with variable return type using "auto"
I am trying to write a function that returns different 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 I am getting:
- Warning: the parseParameterValue function uses the "auto" type specifier with no return type
- Error on second return: inconsistent output for "auto": "int" followed by "double"
Is there a way to make it work?
Thanks in advance.
+3
source to share
2 answers
You can return an erasure type, for example boost::any
, which any type can store. Then your code will 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()};
}
}
+3
source to share