![](/img/trans.png)
[英]Initialize a constexpr std::array with the size of an n-dimensional std::array
[英]Get the size of multi dimensional std::array at compile time via constexpr or template function
我使用三维std::array
,因为在编译时已经知道大小。 但是,我注意到size()函数不是静态的,因此constexpr / template函数无法访问。
我已经在下面找到了演示示例,该示例估计了一维std::array
的大小。 但是,这不适用于两个或多个维度。 有没有一种方法可以通过编写带有x, y, z, ..
尺寸的附加模板参数dim
的函数来返回其他尺寸?
// Example program
#include <iostream>
#include <string>
#include <array>
// typedefs for certain container classes
template<class T, size_t x>
using array1D = std::array<T, x>;
template<class T, size_t x, size_t y>
using array2D = std::array<std::array<T, y>, x>;
template<class T, size_t x, size_t y, size_t z>
using array3D = std::array<std::array<std::array<T, z>, y>, x>;
template<class T, std::size_t N>
auto array_size_helper(const array1D<T, N>&) -> std::integral_constant<std::size_t, N>;
template<class Array>
using array_size = decltype(array_size_helper(std::declval<const Array&>()));
template<class Array>
constexpr auto static_size() -> decltype(array_size<Array>::value) {
return array_size<Array>::value;
}
template<class Array>
constexpr auto static_size(Array const&) -> decltype(static_size<Array>()) {
return static_size<Array>();
}
int main()
{
std::cout << static_size<array3D<float, 3, 4, 5>>();
}
对于一维情况,您也可以使用为std::array
定义的std::tuple_size
:
int main()
{
std::cout << std::tuple_size<array3D<float, 3, 4, 5>>();
}
关于你的实际问题。 如果我理解正确,那么您希望在尺寸函数上有一个附加参数,您可以通过该参数选择要返回尺寸的尺寸,对吗?
使用递归可以很容易地做到这一点。 这是一个工作示例:
// Example program
#include <iostream>
#include <string>
#include <array>
// typedefs for certain container classes
template<class T, size_t x>
using array1D = std::array<T, x>;
template<class T, size_t x, size_t y>
using array2D = std::array<std::array<T, y>, x>;
template<class T, size_t x, size_t y, size_t z>
using array3D = std::array<std::array<std::array<T, z>, y>, x>;
template <size_t dim, typename Array>
struct size_of_dim;
// specialization for std array and first dimension
template <typename T, size_t N>
struct size_of_dim<0, std::array<T,N>> : std::integral_constant<size_t, N> {};
// specialization for std array and dimension > 0 → recurse down in dim
template <size_t dim, typename InnerArray, size_t N>
struct size_of_dim<dim, std::array<InnerArray,N>> : size_of_dim<dim-1,InnerArray> {};
int main()
{
std::cout << size_of_dim<0,array3D<float, 3, 4, 5>>() << std::endl;
std::cout << size_of_dim<1,array3D<float, 3, 4, 5>>() << std::endl;
std::cout << size_of_dim<2,array3D<float, 3, 4, 5>>() << std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.