【发布时间】:2012-05-12 13:15:27
【问题描述】:
clone 范式用于制作派生类的副本,而无需向下转换为基类类型。不幸的是,clone 必须在每个子类中实现(或使用带有 CRTP 的 mixin)。
C++11 的decltype 有没有可能让这变得不必要?
我不认为下面的代码实际上复制了original,而只是指向它的引用。当我尝试使用new decltype(*original) 时,出现错误:
error: new cannot be applied to a reference type.
clone 仍然是 C++11 的路吗?或者有什么新方法可以使用 RTTI 从基类指针复制派生类对象?
#include <iostream>
struct Base
{
virtual void print()
{
std::cout << "Base" << std::endl;
}
};
struct Derived : public Base
{
int val;
Derived() {val=0;}
Derived(int val_param): val(val_param) {}
virtual void print()
{
std::cout << "Derived " << val << std::endl;
}
};
int main() {
Base * original = new Derived(1);
original->print();
// copies by casting down to Base: you need to know the type of *original
Base * unworking_copy = new Base(*original);
unworking_copy->print();
decltype(*original) on_stack = *original;
on_stack.print();
return 0;
}
【问题讨论】: