C++ wrapper with same name?

可紊 提交于 2019-12-23 18:01:54

问题


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


回答1:


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



回答2:


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:


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.




回答4:


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.




回答5:


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?



来源:https://stackoverflow.com/questions/565459/c-wrapper-with-same-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!