C ++中的可重用成员函数 [英] Reusable member function in C++

查看:107
本文介绍了C ++中的可重用成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此成员函数获取指向对象的指针:

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

我试图找到方法,但找不到有用的东西,也许不是可能。我在C ++ 17上使用MSVC编译器

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

推荐答案

您可以从 this 指针为

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

实时

PS:请注意,您仍然需要在每个派生类中重写成员函数。根据您的需求,使用 CRTP ,您可以实施在基类中创建。例如,

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() {}
};

然后

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

在线

这篇关于C ++中的可重用成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆