Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ choose function by return type [duplicate]

I realize standard C++ only picks functions by argument type, not return type. I.e I can do something like:

void func(int);
void func(double);

but not

double func();
int func();

Where in the former, it's clear, in the latter, it's ambigious. Are there any extensions that lets me tell C++ to pick which function to use also by return type?

Thanks!

like image 587
anon Avatar asked Apr 26 '10 22:04

anon


1 Answers

You cannot have two functions in the same scope that have the same name and signature (ie. argument types). Yet you can create a function that will behave differently depending on what variable you assign the result to, as in:

int x=f();
double x=f(); // different behaviour from above

by making f() return a proxy with an overloaded cast operator.

struct Proxy
{
  operator double() const { return 1.1; }
  operator int() const { return 2; }
};

Proxy f()
{
  return Proxy();
}

See http://ideone.com/ehUM1

Not that this particular use case (returning a different number) is useful, but there are uses for this idiom.

like image 175
jpalecek Avatar answered Nov 09 '22 13:11

jpalecek