gpt4 book ai didi

c++ - 如何轻松编写克隆方法?

转载 作者:太空狗 更新时间:2023-10-29 21:22:54 26 4
gpt4 key购买 nike

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

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) 有帮助吗?

最佳答案

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

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

关于c++ - 如何轻松编写克隆方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19607609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com