C ++ 11的decltype是否不需要克隆? [英] Does C++11's decltype make clone unnecessary?

查看:166
本文介绍了C ++ 11的decltype是否不需要克隆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

克隆范例用于创建派生类的副本,而不向下转换为基类类型。不幸的是, clone 必须在每个子类中实现(或与CRTP混用)。

The clone paradigm is used to make a copy of a derived class without casting down to the base class type. Unfortunately, clone must be implemented in each subclass (or with a mixin with CRTP).

C ++ 11的 decltype 使这不必要?

Is there any chance that C++11's decltype makes this unnecessary?

我不认为下面的代码实际上复制了原始,但只是指向它的引用。当我尝试使用 new decltype(* original)时,我得到一个错误:
错误:new不能应用于引用类型

I don't think the code below actually copies original, but simply points a reference to it. When I tried to use new decltype(*original), I get an error: error: new cannot be applied to a reference type.

克隆仍然可以在C ++ 11中使用吗?或者有一些新的方法使用RTTI从基类指针复制派生类对象?

Is clone still the way to go in C++11? Or is there some new way to use RTTI to copy a derived class object from a base class pointer?

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


推荐答案

decltype 是一个静态构造。像所有的C ++类型构造一样,它不能推导出对象的 runtime 类型。 decltype(* original)只是 Base&

decltype is a static construct. Like all C++ typing constructs, it cannot deduce the runtime type of an object. decltype(*original) is just Base&.

这篇关于C ++ 11的decltype是否不需要克隆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆