C++ automatic shared_ptr type in class with macro

Viewed 299

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

you can use the following macro:

#define DEFINE_SHARED(x) using Ptr = std::shared_ptr<x>;

and then use it like:

class Foo {
/* ... */
public:

    DEFINE_SHARED(Foo)
};

#define CreateClass(classname) class classname { \
    using Ptr = std::shared_ptr<classname>;

#define CreateStruct(classname) struct classname { \
    using Ptr = std::shared_ptr<classname>;

It's pretty ugly, but would do the trick.

Example:

class MyClass {
    using Ptr = std::shared_ptr<MyClass>;

    virtual ~MyClass() = default;

    /* .... */
};

// Equivalent to:

CreateClass(MyClass)

    virtual ~MyClass() = default;

    /* .... */

};

@EDIT

Expanding the macro a little bit, you can add base classes:

#define _ClassCreation1(classname) class classname { \
    using Ptr = std::shared_ptr<classname>;

#define  _ClassCreation2(classname, baseclasses) class classname : baseclasses { \
    using Ptr = std::shared_ptr<classname>;

#define _ARG2(_0, _1, _2, ...) _2
#define NARG2(...) _ARG2(__VA_ARGS__, 2, 1, 0)

#define _ONE_OR_TWO_ARGS_1(a) _ClassCreation1(a)
#define _ONE_OR_TWO_ARGS_2(a, b) _ClassCreation2(a,b)

#define __ONE_OR_TWO_ARGS(N, ...) _ONE_OR_TWO_ARGS_ ## N (__VA_ARGS__)
#define _ONE_OR_TWO_ARGS(N, ...) __ONE_OR_TWO_ARGS(N, __VA_ARGS__)

#define CreateClass(...) _ONE_OR_TWO_ARGS(NARG2(__VA_ARGS__), __VA_ARGS__)

(based on: https://stackoverflow.com/a/11763196/5589708)

So you would use it like:

CreateClass(MyClass)

    virtual ~MyClass() = default;

    /* .... */
};

CreateClass(MyClass2, public MyClass)

    virtual ~MyClass2() = default;

    /* .... */

};
Related