如何轻松编写克隆方法?

时间:2013-10-26 14:03:04

标签: c++

我有一个带有虚拟克隆新方法的基类

class A
{
    virtual A* cloneNew() const { return new A; }
};

及其衍生物

class A1 : public A
{
    virtual A1* cloneNew() const { return new A1; }
};

class A2 : public A
{
    virtual A2* cloneNew() const { return new A2; }
};

现在我想使用宏或其他方式使其重新实现更容易,如

class A1: public A
{
    CLONE_NEW; // no type A1 here
};

有可能吗? decltype(this)有帮助吗?

1 个答案:

答案 0 :(得分:3)

以下对我来说很好,可以很容易地变成一个宏:

struct Foo
{
    virtual auto clone() -> decltype(this)
    {
        return new auto(*this);
    }
};

如果您希望clone()函数为const,则无法使用new auto,并且您必须更加努力地使用返回类型:

#include <type_traits>

virtual auto clone() const -> std::decay<decltype(*this)>::type *
{
    return new std::decay<decltype(*this)>::type(*this);
}