Search code examples
c++templatesoverloadingreturn-typeauto

Conversion and overload deduction based on return type


I've seen in the C++ core guidelines that it is preferable to return output values from functions.

I am trying to understand if this is convenient for generic code.

For instance, in order to convert from a string to a certain value I'd normally do something like:

template<class T>
T convertTo(const std::string& value)
  {
  // Do conversion
  return convertedValue;
  }

// Usage
convertTo<float>("test");

Without specifying the type I'd do:

template<class T>
void convertTo(const std::string& value, T& outputValue)
  {
  // Do conversion
  // outputValue = convertedType
  }

// Usage
float myVar{};
convertTo("test", myVar);

I know also that you can do something like:

auto convertTo(const std::string& value, anotherInputPerhaps) ->decltype(myexpression)
  {
  // get the type to return basing on anotherInputPerhaps
  return /*convertedValue*/
  }

The problem here is how to get the right converted value, possibly without passing any input or maybe using a defaulted value. Is this possible?

Thanks

[EDIT] Looking for something that does not introduce overhead


Solution

  • With default value you can also do:

    template<class T>
    T convertTo(const std::string& value, T default_value)
    {
       // DO Conversion
       if( conversion success)
         return convertedValue;
       else 
         return default_value;
    }
    

    And call it like this:

    float myVar= DEFAULT_VALUE;
    myVar = convertTo("test", myVar);