如何自动更新重写方法的 *this 返回类型
How to automatically update a *this return type for overridden methods?
从
类的方法返回 *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;
}
当然,您必须在要链接的每种方法中进行铸造。
相关文章:
- 如何获取std::result_of函数的返回类型
- 奇怪的结构&GCC&clang(void*返回类型)
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 为什么与常规GCC不同,即使有"学究性错误",MinGW-GCC也能容忍丢失的返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 函数作为模板参数,是否对返回类型强制约束
- C++中函数的向量返回类型引发错误
- 检查函数返回类型是否与STL容器类型值相同
- 为什么返回类型中需要typename?C++
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 推导 std::vector::back() 的返回类型
- 在 c++ 中将函数返回类型指定为模板参数
- 这个函数指针的尾部返回类型为"this"合法吗
- 如何自动更新重写方法的 *this 返回类型
- 在成员函数尾部返回类型中使用this和属性
- 方法的C++继承,但返回类型错误(自动转换?typeid(*this)?)