Author Topic: overloading functions by return type  (Read 4836 times)

Offline Acki

  • Multiple posting newcomer
  • *
  • Posts: 100
overloading functions by return type
« 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
« Last Edit: February 11, 2006, 04:16:47 pm by Acki »

Offline mandrav

  • Project Leader
  • Administrator
  • Lives here!
  • *****
  • Posts: 4315
    • Code::Blocks IDE
Re: overloading functions by return type
« Reply #1 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...
Be patient!
This bug will be fixed soon...

Offline AkiraDev

  • Multiple posting newcomer
  • *
  • Posts: 71
Re: overloading functions by return type
« Reply #2 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
« Last Edit: February 11, 2006, 07:33:53 pm by AkiraDev »