Please disable your adblock and script blockers to view this page

Overloading by Return Type in C++




No matching tags

No matching tags


No matching tags

Positivity     41.00%   
   Negativity   59.00%
The New York Times
Write a review: Hacker News

i will be of type to_string_t and not int.We can achieve the original goal of an overloaded function by simply returning to_string_t:Alternatively, one can adhere to almost always auto and write:This technique also works when calling other functions:And even interacts properly with more complex, potentially templated objects:Note how emplace_back is templated and internally constructs an int from our to_string_t.Finally, if (cond) tries to convert cond to bool and thus also works:These examples can be seen in action at godbolt.While we can achieve overloading by return type in many cases using the conversion operator technique, it doesn’t always apply. (The error message for that is slightly ghastly as we have at least 16 candidate overloads.)Finally, only one user-defined conversion can be applied implicitly, so the following doesn’t work:The compiler only tries to directly convert to_string_t to bar:All these cases can be resolved by explicitly adding a cast to the desired type, e.g. int(to_string("10")).One important aspect of normal function overloading in C++ is the extensibility of the overload set. We could also use tag dispatch or even normal overloading, e.g. by delegating to (a user-extensible) void convert_to(std::string_view s, T& v) that is overloaded on the second parameter.For reference, our extensible and checkable version of return-type overloading in C++:Anyone can register new types, optionally using SFINAE to conditionally support them:has_from_string<T> can be used to test (at compile time) if a from_string is available for a certain type:Finally, we still retain the original usage that looks like a return-type overloaded function:As always, a godbolt link to back up my claims.Overloading by argument types is ubiquitous in modern imperative languages but overloading by return type is usually not supported.

As said here by