We all know that you can overload a function according to the parameters:
int mul(int i, int j) { return i*j; }
std::string mul(char c, int n) { return std::string(n, c); }
Can you overload a function according to the return value? Define a function that returns different things according to how the return value is used:
int n = mul(6, 3); // n = 18
std::string s = mul(6, 3); // s = "666"
// Note that both invocations take the exact same parameters (same types)
You can assume the first parameter is between 0-9, no need to verify the input or have any error handling.
If you wanted to make
mul
be a real function instead of a class, you could just use an intermediate class:This lets you do things like passing
mul
as a function into std algorithms:Not that I would use that.
Hmmm, the following code project article seems to do what you are after. Must be magic ;)
Not in C++. What you'd get in the above example would be the returned value which is an int cast into something
string
can understand, most likely achar
. Which would be ASCII 18 or "device control 2".You have to tell the compiler which version to use. In C++, you can do it three ways.
Explicitly differentiate the calls by typing
You somewhat cheated because you sent an integer to a function waiting for a char, and wrongly sent the number six when the char value of '6' is not 6 but 54 (in ASCII):
The right solution would be, of course,
This was worth mentioning, I guess, even if you did not want the solution.
Explicitly differentiate the calls by dummy pointer
You can add a dummy parameter to each functions, thus forcing the compiler to choose the right functions. The easiest way is to send a NULL dummy pointer of the type desired for the return:
Which can be used with the code:
Explicitly differentiate the calls by templating the return value
With this solution, we create a "dummy" function with code that won't compile if instantiated:
You'll note this function won't compile, which is a good thing because we want only to use some limited functions through template specialization:
Thus, the following code will compile:
But this one won't:
Explicitly differentiate the calls by templating the return value, 2
Right, I did use the same parameters for the two "overloaded" functions. But you did start the cheating (see above)...
^_^
More seriously, if you need to have different parameters, then you will to write more code, and then have to explicitly use the right types when calling the functions to avoid ambiguities:
And this code would be used as such:
And the following line:
Would still not compile.
Conclusion
I love C++...
:-p
Use implicit conversion in an in between class.
You get the idea, terrible idea though.