What you want is not (easily) viable in C++. The return value of a function is defined by the function name and the arguments it is given (ie: the result of overload resolution). Your hypothetical num_convert("55")
and num_convert("5555555555")
expressions both take the same argument type. Therefore, they must (usually) call the same function which returns the same value.
Thus, the simplest way to achieve what you want would be for such a function to return a proxy object that stores the argument it is given. The proxy would have conversion operators (operator int
, operator long
, etc) which would perform the actual conversion.
Of course, this means that auto i = num_convert("55")
will not actually do the conversion. If the function was given a temporary, i
would contain a reference to that temporary. Which means that any uses of i
would be broken, since they would reference a temporary whose lifetime has ended.
The standard doesn't have a function like this.
It would be better to write the type explicitly into the call as a template parameter and then use auto
deduction instead of using a proxy: auto i = num_convert<int>("55");
. The standard has no such function either. But really, there's not much difference between num_convert<int>
and stoi
, so just use it.