tags:

views:

377

answers:

5

How can I do a wrapper function which calls another function with exactly same name and parameters as the wrapper function itself in global namespace?

For example I have in A.h foo(int bar); and in A.cpp its implementation, and in B.h foo(int bar); and in B.cpp foo(int bar) { foo(bar) }

I want that the B.cpp's foo(bar) calls A.h's foo(int bar), not recursively itself.

How can I do this? I don't want to rename foo.

Update:

A.h is in global namespace and I cannot change it, so I guess using namespaces is not an option?

Update:

Namespaces solve the problem. I did not know you can call global namespace function with ::foo()

+4  A: 

use a namespace

namespace A
{
int foo(int bar);
};
namespace B
{
int foo(int bar) { A::foo(bar); }
};

you can also write using namespace A; in your code but its highly recommended never to write using namespace in a header.

acidzombie24
@wrap-per - You mention in an edit that you cannot change `A`, note that this can still work if you can change `B` to be in a namespace - B::foo() simply needs to call A's foo() using `::foo(bar)` to indicate that it wants to call the foo() in the global namespace.
Michael Burr
+1  A: 

This is the problem that namespaces try to solve. Can you add namespaces to the foo's in question? Then you have a way of resolving this. At any rate, you would hit linker issues if both of them are in global namespace.

dirkgently
A: 

As mentioned above, namespace is one solution. However, assuming you have this level of flexibility, why don't you encapsulate this function into classes/structs?

+2  A: 

does B inherit/implement A at all?

If so you can use

int B::foo(int bar) 
{ 
   ::foo(bar); 
}

to access the foo in the global namespace

or if it does not inherit.. you can use the namespace on B only

namespace B
{
int foo(int bar) { ::foo(bar); }
};
ShoeLace
+1  A: 

You can't do this without using namespaces, changing the name of one of the functions, changing the signature, or making one of them static. The problem is that you can't have 2 functions with the same mangled name. So there needs to be something that makes them different.

KeithB