使用可变参数模板函数的内置多维数组的大小
在 C++11 中,可以使用 constexpr 创建一个在编译时返回内置一维数组的大小(元素数量)的函数。下面的示例:
template <typename T, std::size_t N>
constexpr std::size_t size(T (&array)[N])
{
return N;
}
在我看来,这是 ARRAY_SIZE 和类似宏的更好替代方案。
但是,这只会返回内置多维数组的最高有效维度的大小。
我使用以下函数来确定内置二维数组的大小:
template <typename T, std::size_t N, std::size_t N2>
constexpr std::size_t size(T (&array)[N][N2])
{
return N * N2;
}
理想情况下,拥有一个返回任意维数的内置数组的大小的函数将非常有用。我认为可变参数模板可能会有所帮助,但我看不到一种解压模板参数的方法,因为只传递了一个参数。这样的功能可以吗?
提前致谢。
In C++11 it is possible to create a function which returns the size (number of elements) of a built-in one dimensional array at compile time using constexpr. Example below:
template <typename T, std::size_t N>
constexpr std::size_t size(T (&array)[N])
{
return N;
}
This is a superior alternative to ARRAY_SIZE and similar macros imo.
However, this will only return the size of the most significant dimension of a built-in multidimensional array.
I use the following function for determining the size of a built-in two dimensional array:
template <typename T, std::size_t N, std::size_t N2>
constexpr std::size_t size(T (&array)[N][N2])
{
return N * N2;
}
Ideally, it would be very useful to have a function that returns the size of a built-in array with an arbitrary number of dimensions. I thought variadic templates may help but I couldn't see a way of unpacking the template paramters as only one argument is passed. Is such a function possible?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
例子:
Example:
您正在寻找
std::extent
。 C++11 §20.9.5:用法,也来自标准,根据需要使用
std::
前缀extent
:您可能还应该使用它来替换您的自定义
size
函数。编辑:哎呀,现在我读到了问题的结尾:vP。您还需要
std::remove_extent
。You're looking for
std::extent
. C++11 §20.9.5:Usage, also from the Standard, prefix
extent
withstd::
as needed:You should also probably use this to replace your custom
size
function.Edit: Oops, now I read to the end of the question :vP . You also need
std::remove_extent
.