【发布时间】:2015-10-30 23:21:20
【问题描述】:
所以,我有一个类,它有一个数组数组作为私有成员。我希望每种情况(一维或二维)都有两个构造函数。但当然,他们的声明恰好是相同的,所以如果我不做一些事情,模板推导就无法完成它的工作。代码如下:
编辑:我还需要它来处理向量或 C++ 数组等 STL 容器。这就是为什么我过于复杂并且不使用“数组”修复。
#include <iostream>
#include <array>
template<class T, std::size_t rows_t, std::size_t cols_t>
class test
{
private:
std::array<std::array<T, cols_t>, rows_t> _data;
public:
auto begin() { return this->_data.begin(); }
auto end() { return this->_data.end(); }
//CONSTRUCTOR
template<class type_t>
test(const type_t &arr)
{
std::size_t j = 0;
for (const auto &num : arr)
this->_data[0][j++] = num;
}
template<class type_t>
test(const type_t &arr)
{
std::size_t i = 0;
for (const auto &el : arr)
{
std::size_t j = 0;
for (const auto &num : el)
this->_data[i][j++] = num;
++i;
}
}
};
int main()
{
double arr[3] = { 1, 2, 3 };
double arr2[2][2] = { {1, 2}, {3, 4} };
test<double, 1, 3> obj = arr;
test<double, 2, 2> obj2 = arr2;
for (const auto &i : obj2)
{
for (const auto &j : i)
std::cout << j << " ";
std::cout << std::endl;
}
std::cin.get();
}
注意:我一直在阅读有关 enable_if 的信息,但我不太了解它是如何工作的。能做到吗?
【问题讨论】:
-
当您知道
_data是二维的时,为什么还需要两个案例? -
为了方便。有时 _data 可能有 1 行和 3 列,使其成为一维的。
-
您可以使用一维数组作为任何维度数组的后备数据结构并计算索引(至少在它们密集的情况下)。这将消除问题。但坦率地说,你已经有了一维数组(
std::array),而二维数组应该是一个单独的数据类型(类)。 -
auto begin() { return this->_data.begin(); }这将返回外部维度的迭代器。你确定这是你想要的吗? -
是的,我很确定。这就是我能够在示例末尾执行 ranged-for 循环的方式。
标签: c++ templates c++11 sfinae enable-if