Reusable member function in C++

烈酒焚心 提交于 2020-07-20 10:05:23

问题


I'm using this member function to get pointer to object:

    virtual Object* Create()
    {
        return new Object();
    }

It's virtual so I can get pointer to derived objects, now I'm doing it like this:

    virtual Object* Create()
    {
        return new Foo();
    }

It is working correctly, but I'd like to do something like this to prevent any mistakes and also to make it easier so I don't have to rewrite that function every time I make new class:

    virtual Object* Create()
    {
        return new this();
    }

I was trying to find how to do this but couldn't find anything useful, maybe it's not possible. I'm using MSVC compiler with C++17


回答1:


You can get the type from this pointer as

virtual Object* Create() override
{
    return new std::remove_pointer_t<decltype(this)>;
}

LIVE

PS: Note that you still need to override the member function in every derived class. Depending on your demand, with CRTP you can just implement Create in the base class. E.g.

template <typename Derived>
struct Object {
    Object* Create()
    {
        return new Derived;
    }
    virtual ~Object() {}
};

then

struct Foo : Object<Foo> {};
struct Bar : Object<Bar> {};

LIVE



来源:https://stackoverflow.com/questions/62932475/reusable-member-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!