C++ 11的decltype是否不需要克隆?

use*_*ser 11 c++ clone c++11

克隆模式被用来做派生类的副本,而不拆毁到基类.不幸的是,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;
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*las 21

decltype是一个静态构造.与所有C++类型构造一样,它不能推断出对象的运行时类型.decltype(*original)只是Base&.

  • 您可以使用std :: decay将Base转换为Base. (4认同)
  • 这个答案(以及我的答案的先前版本)是危险的错误.`decltype(*original)`实际上是`Base&`. (2认同)