问题描述
我有两个版本的第三方C ++库(lib.so和头文件) 在一个版本中,所有类/枚举/结构都在名称空间“ A”中 在其他版本中,它们位于名称空间“ B”中 两个版本的标头和lib.so名称都相同
我如何拥有相同的代码库,以便可以支持两个版本。像这样
if (myVersion == "1.0") {
/* pick all the symbols from namespace "A"*/
} else {
/* pick all the symbols from namespace "B"*/
}
解决方法
您在代码中建议的是在运行时确定它,这在C ++中是不可能的。
如果您的版本是常量,则可以将其声明为宏,然后使用预处理器进行条件处理。
如评论中所述,不建议使用using namespace
并且命名空间别名可以更好。
#if VERSION == 1000 //...
namespace My = A;
#else
namespace My = B;
#endif
//使用我的:: ...
但是,如果您坚持使用using namespace
,
#define VERSION //your version
...
#if VERSION == 1000 //or something like that to mark 1.0.0.0
using namespace A;
#else
using namespace B;
#endif
,
使用下面的代码,我创建了两个包装器.so(一个具有版本1 lib和-DVERSION = 1,另一个具有版本2 lib和-DVERSION = 2) 假设它们是wlib1.so和wlib2.so
我将位于命名空间A或B(取决于我使用的是什么)中的API封装在外部“ C”中
例如:
function fib(N) {
var arr = [0,1,1];
for (i = 3; i <= N; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}
return arr[N];
}
现在在用户端,我在运行时使用了类似的东西:
#define VERSION //your version
extern "C"
{
#if VERSION == 1 //or something like that to mark 1.0.0.0
using namespace A;
#else
using namespace B;
#endif
void foo_wrapper() {
foo();
// wlib1.so will have A::foo() and wlib2.so will have B::foo()
}
}
因此用户可以在运行时通过版本进行控制。