【发布时间】:2019-07-09 21:32:15
【问题描述】:
对于我的矩阵类,我想在+ - / * % 的 range-v3 视图上执行某种运算符重载(可能使用表达式模板)。
例如,如果我想查看两列的总和,我想写
col_1 + col_2
而不是
rv::zip_with([](auto c1, auto c2) {return c1 + c2;}, col_1, col_2);
可能来自paper 的一些想法可以用来避免构建太多的临时对象。这是我要写的代码:
//simple example
//what I want to write
auto rangeview = col_1 + col_2;
//what I can write
auto rangeview = rv::zip_with([](auto c1, auto c2) {
return c1 + c2;
}, col_1, col_2);
//itermediate
//what I want to write
auto rangeview = col_1 + col_2 + col_3;
//what I can write
auto rangeview = rv::zip_with([](auto c1, auto c2, auto c3) {
return c1 + c2 + c3;
}, col_1, col_2, col_3);
//advanced
//what I want to write
auto rangeview = 10*col_1 + 20*col_2 - 30*col_3;
//what I can write
auto rangeview = rv::zip_with([](auto c1, auto c2, auto c3) {
return 10.0*c1 + 20.0*c2 - 30.0*c3;
}, col_1, col_2, col_3);
//more advanced with elementwise multiplication
//what I want to write
auto rangeview = 10*col_1 + 20*col_2 - col_2 % col_3;
//what I can write
auto rangeview = rv::zip_with([](auto c1, auto c2, auto c3) {
return 10.0*c1 + 20.0*c2 - c2*c3;
}, col_1, col_2, col_3);
【问题讨论】:
-
这是一个非常非常广泛的问题。您所要求的实际上是一个表达式模板库 - 并且有许多大型库试图在各个领域解决此类问题。
-
那么中间示例(只是添加任意数量的视图)呢?还是太宽泛了?
-
常规运算符重载有什么问题?
-
通过常规重载,您必须按照上面的论文(第 11 页)中的说明构建临时对象。
-
您可以使用
std::plus<>(或ranges::plus)来简化一点。
标签: c++ operator-overloading c++17 range-v3