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

标签 c++ inheritance overriding this return-type

<分区>

从类的方法中返回 *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;
}

当然,您必须在要链接的每个方法中进行转换。

关于c++ - 如何自动更新重写方法的 *this 返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29984222/

相关文章:

css - Twitter Bootstrap 的元素边框颜色

c++ - 我在哪里可以学习有关C++编译器的 “what I need to know”?

c++ - 初学者引用类型参数混淆

c++ - 函数调用中的堆栈分配

ruby-on-rails - Rails 3 模型子类让我发疯!请帮助更正 urls/params 哈希

delphi - 重写Delphi函数System.Round

C++:返回 NULL 而不是结构

java - super() 构造函数中的初始化问题

C++ 继承运算符<<

javascript - 如何在 JS (Javascript) 中重载对象的构造函数?