Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ automatic shared_ptr type in class with macro

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
};
like image 996
Nicola Lissandrini Avatar asked Jun 20 '26 21:06

Nicola Lissandrini


1 Answers

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.

like image 111
Joel Bodenmann Avatar answered Jun 22 '26 12:06

Joel Bodenmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!