2013-10-26 118 views
3

我有一个基类与虚拟克隆新方法如何轻松编写克隆方法?

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

+0

拥有克隆方法通常表示设计中存在错误(代码异味)。你真的想做什么? –

+1

@Loki Astari你能否详细说明为什么克隆方法是代码味道? – Max

+0

@LokiAstari我在GUI的树中有动态类型的项目。我想在单击某个项目时创建一个新的类似项目。 – user1899020

回答

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

@ user1899020 MSVC11(VS2012的C++编译器)[完全不支持C++ 11](http://msdn.microsoft.com/zh-cn/我们/库/ vstudio/hh567368.aspx)。另一方面,据我所知MSVC11支持尾随返回类型和'decltype'说明符,所以问题应该在执行'std :: decay'。什么是你的编译器错误? – Manu343726

+0

MSVC11显示'this'只能用在类的非静态方法的内部体中。问题出在' - > decltype(this)' – user1899020

+1

@ user1899020我试过了,在我的VS2012安装过程中也失败了。看起来像一个MSVC11错误。 – Manu343726