3
votes

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()

5
As long as B.h can be changed to put its foo() into a namespace, then you can still do it. - Greg Rogers
namespaces is not an option? You want B to use A's namespace right? and you cant change A namespace? so whats the problem, you never need to change A. Make B call A::foo() and if you cant change B then theres nothing to do bc it seems like you cant change anything ;) - user34537

5 Answers

4
votes

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.

3
votes

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

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.

1
votes

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.

0
votes

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?