我正在编写需要共享指针的跨平台代码。出于我无法控制的原因,我们现在还不能使用C++11。因此,我建议使用boost::shared_ptr。当我们采用C++11时(可能是一年后),我们应该能够用std智能指针替换boost智能指针。我的问题是使用boost的最佳方法,以便以后更容易切换。模板混叠不可用,因此如下所示:
namespace my {
template <typename T>
using shared_ptr = boost::shared_ptr<T>;
}将shared_ptr封装到另一个结构中的另一种技术会导致丑陋和不可读的APIs,因为我将不得不使用它,因此my::shared_ptr<int>::type。
namespace my {
template<typename T>
struct shared_ptr
{
typedef boost::shared_ptr<T> type;
};
}我正在寻找替代方案。如有任何建议,将不胜感激。
编辑:我考虑过的另一个选择是:
namespace my {
using boost::shared_ptr;
}然后使用my::shared_ptr<int>。稍后,我将将boost更改为std in namespace my。然而,我无法决定每一种方法的赞成和反对来达成一个决定。
发布于 2014-04-08 06:10:31
与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( 4)以上三者相结合。
匿名命名空间可以帮助将using语句保持在文件的本地,因此您可以对每个源文件进行控制,例如:
namespace{
using std::shared_ptr;
}(我个人一直使用2 )。
发布于 2014-04-08 07:09:57
我们在我们的项目中做了这样的事情:
#if compiler_doesnt_support_c++11
#include <boost/shared_ptr.hpp>
namespace std {
using boost::shared_ptr;
}
#elif compiler_has_c++11_in_tr1
#include <memory>
namespace std {
using std::tr1::shared_ptr;
}
#else
#include <memory>
#endif只需在代码中使用std::shared_ptr。
是的,这在技术上是未定义的行为(因为您不允许向::std命名空间添加类似的名称),但多年来它一直没有出现任何问题。
https://stackoverflow.com/questions/22928795
复制相似问题