实现返回 *this 的 "virtual" 方法(协变返回类型)



我正在编写C++类的层次结构,比如AB继承AC继承AD继承B

现在,所有这些类都必须有一个方法bar() &,其主体是:

{
A::foo();
return *this;
}

这是完全相同的代码,做完全相同的事情——除了返回值的类型——它返回对类类型的左值引用。

现在,这个方法的签名对于每个类都是不同的。但是,这基本上是相同的方法。问题是,按照目前的情况,我需要多次复制代码。如何避免这种代码重复?

我本来想用CRTP写一些混音,但当我深入到细节时,它变得非常丑陋。

注意:为了这个例子的目的,bar()只为左值定义,以免涉及从右值返回*this的合法性问题。

正如Raymond Chen所评论的,c++23会推导出这样的代码:

struct A
{
template <typename Self>
Self& bar(this Self& self) // Here self is the static type which calls bar
// so potentially the derived type
{
self.A::foo(); // or self.foo();
return self;
}
// ...
};
struct B : A{};
struct C : A{};
struct D : B{};

但目前,CRTP可能会有所帮助,比如:

struct A
{
// ...
};

template <typename Derived, typename Base>
struct A_CRTP : Base
{
Derived& bar()
{
A::foo();
return static_cast<Derived&>(*this);
}
// ...
};
struct B : A_CRTP<B, A> {};
struct C : A_CRTP<C, A> {};
struct D : A_CRTP<D, B> {};

最新更新