所以,我有一个类,它有一个数组数组作为私有(private)成员。我希望每种情况有两个构造函数(1D 或 2D)。但当然他们的声明恰好是相同的,所以如果我不做一些事情,模板推导就无法完成它的工作。代码如下:
编辑:我还需要它与 vector 或 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
的内容,但我不太明白它是如何工作的。这样可以吗?
最佳答案
构造函数不应相同,但您只提供了最通用的可能匹配。
这里不需要 SFINAE。只需为一维数组提供一个构造函数,为二维数组提供一个单独的构造函数即可:
template <typename T2, std::size_t N>
test( const T2 (&a)[N] )
{
...
}
template <typename T2, std::size_t M, std::size_t N>
test( const T2 (&a)[M][N] )
{
...
}
另一个注意事项:POSIX 保留以“_t”结尾的类型名,因此在您自己的代码中避免使用它们通常是一个好主意。 (令人讨厌,我知道。)标准 C++ 将使用以下形式的驼峰命名法:RowsType
等,然后为以下用户使用 typedef 一个 rows_type
类。
但是请注意,rows_t
实际上并不是一种类型,它是一个值。更好的名称应该是 NRows
.
希望这有帮助。
关于c++ - 区分模板类构造函数中的 1D 和 2D 容器 (SFINAE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33446246/