P0847推论到这一点-它可以允许通用克隆而不需要CRTP吗?

问题描述

P0847提出了对成员函数使用显式this参数的可能性。

此提案带来的其他优点中,CRTP without C,R and even T也有很大的新可能性。

在C ++中实现通用clone的一种常见做法是基于CRTP,例如参见this SO post

鉴于我们需要clonevirtual(或至少表现为虚拟),才能:

Shape* pcopy = pShape->clone(); // get a copy of the correct runtime type

考虑到提议是具有显式参数的成员函数,请勿声明为virtual

是否仍然可以使用P0847来实现具有动态行为且没有CRTP的通用克隆

解决方法

模板推导仅使用静态类型,而if akey == "color[]" or akey == "execute" or akey == "task1" or akey=="task2": second_form[akey] = elements.getvalue(akey) 需要动态类型,因此Clone

P0847主要允许进行转化

virtual

进入

template <typename T>
T* Foo(const T& obj);
// With Obj base of T

您可以做的是使用智能指针简化协方差。

template <typename Self>
Self* Obj::Foo(this const Self& obj);

但是CRTP似乎更好,因为它可以避免为每种类型重写struct Clonable { virtual ~Clonable() = default; virtual Clonable* do_clone() const = 0; template <typename Self> std::unique_ptr<Self> clone(this const Self& self) { std::unique_ptr<Self>(self.do_clone()); } }; struct MyClass : Clonable { MyClass* do_clone() const override { return new MyClass(*this); } };

(未来的反思可能会简化do_clone

,

目前尚不清楚此提议是否允许在构造函数上使用显式this

如果可以,我们可以解决这个问题。

struct clonable {
  icloneable const*(*do_clone)(icloneable const*) = 0;
  template<class Derived>
  clonable( this Derived& ):
    do_clone([](icloneable const* vself)->icloneable const*{
      return new Derived(*static_cast<Derived const*>(vself);
    })
  {}
  icloneable const* clone() const {
    return do_clone( this );
  }
};

这依赖于将明确的this传递给构造函数的能力,并且明确的this参数是派生最多的类型。

我们基本上自己实现了一个vtable(只有一个)。

无法执行此操作,您可能需要等待反思。