在同一函数中使用提升multi_array及其视图
Using boost multi_array and its views in the same function
multi_array视图具有许多与multi_array相同的方法。他们是否有一个共同的基础,我可以通过参考使用?
void count(Type a) {
// ^^^^ what should I use here?
cout << a.num_elements() << endl;
}
int main() {
boost::multi_array<int, 2> a;
count(a);
count(a[indices[index_range()][index_range()]]);
}
不,没有共同的基础。您必须使用模板。查看多阵列概念和升压概念检查库。
具体来说,你需要这样做:
template<ArrayType>
void count(ArrayType&& a) {
cout << a.num_elements() << endl;
}
而且由于该操作是非修改的,因此最好void count(ArrayType const& a)
.
在我的多维数组库中,有一个共同的基础,因此您可以通过这种方式避免一些代码膨胀。我仍然会使用模板版本,因为它在概念上更正确。
#include<multi/array.hpp> // from https://gitlab.com/correaa/boost-multi
#include<iostream>
namespace multi = boost::multi;
template<class Array2D>
auto f1(Array2D const& A) {
std::cout<< A.num_elements() <<'n';
}
auto f2(multi::basic_array<double, 2> const& A) {
std::cout<< A.num_elements() <<'n';
}
int main() {
multi::array<double, 2> A({5, 5}, 3.14);
f1( A ); // prints 25
f2( A ); // prints 25
f1( A({0, 2}, {0, 2}) ); // a 2x2 view // prints 4
f2( A({0, 2}, {0, 2}) ); // prints 4
}
https://godbolt.org/z/5djMY4Eh8
相关文章:
- C++11 中不同类型的对象的 std::array 的替代方案
- constexpr begin of a std::array
- C++如果必须在编译时确定大小,std::array 有什么意义?
- 可视化C++:发布模式的运行时库作为'Multi-threaded Debug DLL'
- OpenGL VBO Indexing ( How to compute Index Array)
- 标准::unordered_map 中的 std::array 的值初始化
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 确保编译时的特定 std::array 位置
- std::array的长度有大小限制吗?
- 将 std::array 移动到另一个 std::array
- 首先按给定顺序打印所有数字,然后使用 Array 打印所有字符和其他符号
- 为什么 std::shared_ptr 被认为是"heavy"和"expensive",但 std::array "same perfprmance as plain (c-style) arrays
- 将 **float array 从 C++ Dll 传递给 python
- std::bind on statd::array 的运算符 []
- 检查输入 std::array 指针数据是否等于某个常量数组
- 我可以安全地复制矢量<array>吗?
- 解析问题 - 预期的非限定 ID - #include <array> 编译错误
- 如何读/写或遍历 std::array 中的特定元素范围?
- 通过 host() 从 af::array 检索数据会导致错误的数据
- "dynamically allocated memory emulating multi-dimensional array"的正确术语?