如何自动更新重写方法的 *this 返回类型

How to automatically update a *this return type for overridden methods?

本文关键字:this 返回类型 方法 何自动 更新 重写      更新时间:2023-10-16

类的方法返回 *this 是一个很好的习惯,这样方法调用就可以链接起来。请考虑以下示例:

template <typename T> class container 
{
public:
  container& append(const T& x) { 
    ...
    return *this; 
  }
};
container<int> a;
a.append(1).append(2).append(5);

但是,当从中派生一个新类时,它会破坏链条:

class int_container : public container<int> 
{
public:
  int_container& sort_ascending()  {
    ...
    return *this;
  }
};
int_container b;
b.append(10).sort_ascending();   // error: container::sort_ascending() does not exist

这可以通过复制基类的方法并更新返回类型来解决......

class int_container : public container<int> 
{
  int_container& append(int i)  { container<int>::append(i); return *this; }
  ...
};

。但是,我的基类有 60 个这样的方法,我需要几个派生类。那么,有没有办法更新派生类中这些方法的返回类型,而不必重写每个派生类中的每个方法?并且不使用预处理器宏?

以下是相关代码段的基于 CRTP 的解决方案:

#include <type_traits>
template <typename T, typename R>
struct container_return_type
{
    typedef R& type;
};
template <typename T>
struct container_return_type<T, void>
{
    typedef T& type;
};
template <typename T, typename R = void> class container 
{
public:
     typename container_return_type<container<T>, R>::type append(const T& x) { 
        return static_cast<typename container_return_type<container<T>, R>::type>(*this); 
    }
};
class int_container : public container<int, int_container> 
{
public:
    int_container& sort_ascending()  {
        return *this;
    }
};
int main(int argc, char** argv)
{
    int_container b;
    b.append(10).sort_ascending();
    container<double> c;
    c.append(1.0).append(2.0);
    return 0;
}

当然,您必须在要链接的每种方法中进行铸造。