Code::Blocks Forums

User forums => Help => Topic started by: Acki on February 11, 2006, 04:14:47 pm

Title: overloading functions by return type
Post by: 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
}
But this doesn't work anymore !!! :(

What do I have to set, for this ???

thx, Acki
Title: Re: overloading functions by return type
Post by: mandrav on February 11, 2006, 04:23:22 pm
You cannot overload a function when the only difference is the return type. Never.
Although your example has nothing to do with overloading...
Title: Re: overloading functions by return type
Post by: AkiraDev on February 11, 2006, 07:28:10 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
}
But this doesn't work anymore !!! :(

What do I have to set, for this ???

thx, Acki


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); }

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