带有宏的类中的C++自动shared_ptr类型
我正在尝试为我的项目中的每个类添加一个 shared_ptr 的类内别名,如下所示:
class Foo {
/* ... */
public:
using Ptr = std::shared_ptr<Foo>;
};
这样我就可以使用速记定义指向 Foo 的共享指针Foo::Ptr fooObjPtr;。有没有什么方法可以创建一个自动添加别名的宏?就像是:
#define DEFINE_SHARED using Ptr = std::shared_ptr<__CLASS_NAME__>;
class Foo {
/* ... */
public:
DEFINE_SHARED
};
回答
类模板可以这样做:
template<typename T>
class FooBase
{
public:
using Ptr = std::shared_ptr<T>;
};
class Foo :
public FooBase<Foo>
{
};
int main()
{
Foo::Ptr x = std::make_shared<Foo>();
std::cout << x << std::endl;
}
这应该可以在不依赖任何预处理器功能的情况下实现您的要求。
请注意,根据您的用例,您可能需要添加一些语法糖,例如确保它FooBase::T实际上继承自FooBase. 有几种解决方案 - 查找 CRTP,因为这是一个常见的“问题”。