<分区>
从类的方法中返回 *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 个这样的方法,我需要几个派生类。那么,有没有什么方法可以更新派生类中那些方法的返回类型,而不必覆盖每个派生类中的每个方法呢?并且不使用预处理器宏?