User forums > Help
overloading functions by return type
(1/1)
Acki:
Hi,
I have a little problem with overloading functions.
I think this is a compiler setting or so, but I don't know what...
Well, I could allways overload functions by changing the return type:
--- Code: ---void fnc1(){
// do domething
}
bool fnc1(){
// do domething
}
--- End code ---
But this doesn't work anymore !!! :(
What do I have to set, for this ???
thx, Acki
mandrav:
You cannot overload a function when the only difference is the return type. Never.
Although your example has nothing to do with overloading...
AkiraDev:
--- Quote from: Acki on February 11, 2006, 04:14:47 pm ---Hi,
I have a little problem with overloading functions.
I think this is a compiler setting or so, but I don't know what...
Well, I could allways overload functions by changing the return type:
--- Code: ---void fnc1(){
// do domething
}
bool fnc1(){
// do domething
}
--- End code ---
But this doesn't work anymore !!! :(
What do I have to set, for this ???
thx, Acki
--- End quote ---
I'm curious as to where could you do such a thing before, but no, function overload by return type is not a native C++ feature.
However, IF you really need to do so, there is a trick to achieve the same, using the same syntax, through a temporary object.
Let's say you want a function to return either a boolean or a double.
--- Code: ---bool foo_bool(int n)
{
return true;
}
double foo_double(int n)
{
return 0.0;
}
class return_type_switcher
{
public:
return_type_switcher(int _n) : n(_n) {}
operator bool() { return foo_bool(n); }
operator double() { return foo_double(n); }
private:
int n;
};
return_type_switcher foo(int n)
{ return return_type_switcher(n); }
--- End code ---
This way, you call either version of the function, at cost of a hidden implicit cast of an object.
The other, better, alternative is using a function template instead, which requires you to make the return type explicit every time you instantiate it. Personally I prefer that way, it's safer.
Regards
Navigation
[0] Message Index
Go to full version