mlimber wrote:
Gilles Rochefort wrote:
On Thu, 29 Dec 2005 01:30:35 -0800, skishorev wrote:
Hi,
Here I am taking two functions. void f(int,int) and another one is
float f(int,int).
Is it possible to overload with return values.
Thx,
kishore
C++ do not allow to overload with return values .. But, there is a trick
which consist to return an object which will invoke the appropriate
function via a type conversion operator.
Just consider the following code as an example...
Gilles Rochefort
#include <iostream>
float foo1(int x,int y)
{
return (float)x/(float)y;
}
int foo2(int x,int y)
{
return (x*y);
}
class resultFoo
{
private:
int _x,_y;
public:
resultFoo(int x,int y):_x(x),_y(y)
{}
operator float()
{ return foo1(_x,_y); }
operator int()
{ return foo2(_x,_y); }
};
resultFoo foo(int x,int y)
{
return resultFoo(x,y);
}
int main(void)
{
float a;
int b;
a = foo(3,4);
b = foo(3,4);
std::cout << "foo(3,4) = " << a << std::endl;
std::cout << "foo(3,4) = " << b << std::endl;
}
Another method is to translate the problem into standard overloading by
passing a dummy parameter. Rather than passing a real object, however,
you can use a trick from _Modern C++ Design_ by creating an object that
contains *only* type information and that can easily be optimized away
by the compiler:
template <typename T>
struct Type2Type
{
typedef T OriginalType;
Type2Type() {}
};
void foo( int i, Type2Type<void> ) { /*...*/ }
int foo( int i, Type2Type<int> ) { /*...*/ return i; }
void bar()
{
foo( 42, Type2Type<void>() );
foo( 42, Type2Type<int>() );
}
This trick is also useful for getting around some template problems on
non-conformant compilers (e.g. VC++ 6).
Cheers! --M
[snip]
any more suggestions on getting nonstandard
overloading to work?