I'm trying to add to every class in my project an in-class alias for shared_ptr, like so:
class Foo {
/* ... */
public:
using Ptr = std::shared_ptr<Foo>;
};
so that I can define shared pointers to Foo with the shorthand Foo::Ptr fooObjPtr;. Is there any method to create a macro that automatically adds the alias? Something like:
#define DEFINE_SHARED using Ptr = std::shared_ptr<__CLASS_NAME__>;
class Foo {
/* ... */
public:
DEFINE_SHARED
};
A class template can do this:
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;
}
This should achieve what you're asking for without relying on any pre-processor features.
Note that depending on your use case you might want to add some syntactic sugar such as ensuring that FooBase::T is actually inheriting from FooBase. There are several solutions for that - look up CRTP as that is a common "issue" there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With