341*_*008 6 c++ boost shared-ptr template-aliases
我正在研究需要共享指针的跨平台代码.由于我无法控制的原因,我们还不能使用C++ 11.所以,我建议使用boost :: shared_ptr.当我们采用C++ 11(也许是一年后),我们应该能够用std智能指针替换boost智能指针.我的问题是关于使用boost的最佳方法,以便以后更容易切换.模板别名不可用,因此以下内容如下:
namespace my {
template <typename T>
using shared_ptr = boost::shared_ptr<T>;
}
Run Code Online (Sandbox Code Playgroud)
将shared_ptr包装在另一个struct中的另一种技术导致丑陋且不可读的API,因为我将不得不使用它my::shared_ptr<int>::type:
namespace my {
template<typename T>
struct shared_ptr
{
typedef boost::shared_ptr<T> type;
};
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找替代方案.任何建议将不胜感激.
编辑:我考虑的另一个选择是:
namespace my {
using boost::shared_ptr;
}
Run Code Online (Sandbox Code Playgroud)
然后使用my::shared_ptr<int>.后来我会改变boost,以std在namespace my.但是,我无法决定每种做出决定的方法的原则和结果.
与C++ 98兼容的四个选项,
1)使用impl::shared_pointer<T>.并切换自:
namespace impl = boost; 至 namespace impl = std;
2)(更优雅但风险更大)是在shared_ptr没有命名空间限定的情况下使用,以后再切换
using boost::shared_ptr到using std::shared_ptr.
3)(丑陋但我猜是首选的工业解决方案)一直使用宏.
#if DETECTC++11
#define SHARED_PTR std::shared_ptr
#else
#define SHARED_PTR boost::shared_ptr
#endif
Run Code Online (Sandbox Code Playgroud)
4)结合上面的3.
匿名命名空间可以帮助将using语句保持为文件本地,因此您可以使用每个源文件控制,例如:
namespace{
using std::shared_ptr;
}
Run Code Online (Sandbox Code Playgroud)
(我个人经常使用2.)