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


No, a function can only have one return type.



Note that handling the return type of a function must be done at compile time, but your function uses values ​​that may not be known until run time.

+10


source


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







All Articles