Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
485 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...