不——永远不要这样做!
这是不可能的,你可能会意外崩溃。
正确完成它的唯一方法是使用命名空间重命名:即创建替代
boost 版本放置在 不同的 命名空间中。
最新版本的 BCP 提供了此选项。所以你将使用类似 boost_1_43 的东西来代替 boost。但这对你来说是非常透明的。但你仍然应该知道
其中你不能在同一个 cpp 文件中使用两个版本的 boost。
也看看这个讨论:Creating Library with backward compatible ABI that uses Boost
喜欢的脚本重命名命名空间、定义和包含,因此您实际上可以包含两个
类似的 boost 版本
#include <boost/foo.hpp>
#include <myboost/bar.hpp>
boost::foo f;
myboost::bar b;
Boost BCP 不允许这样做。
但是你仍然应该小心,因为有些库在导出外部“C”符号时没有
boost 前缀,boost::thread 和 boost::regex 的 C API (regexec, regcomp)
编辑
作为此类问题的示例,请创建以下文件:
a.cpp:
template<typename Foo>
Foo add(Foo a, Foo b)
{
return a+b;
}
int foo(int x,int y)
{
return add(x,y);
}
b.cpp:
template<typename Foo>
Foo add(Foo a, Foo b)
{
return a-b;
}
int bar(int x,int y)
{
return add(x,y);
}
test.cpp:
#include <iostream>
int foo(int,int);
int bar(int,int);
int main()
{
std::cout<< foo(10,20) <<" " <<bar(10,20) << std::endl;
}
编译它们:
g++ a.cpp b.cpp test.cpp
你会期望:
30 -10
但你会得到
30 30
或
-10 -10
取决于链接顺序。
所以使用两个 boost 版本你可能会不小心使用来自其他 boost 和 crash 的符号
与此程序中的符号相同 int add<int>(int,int) 甚至被解析为相同的符号
如果放在不同的编译单元中。