我有一个带有虚拟克隆新方法的基类
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)