数组大小元函数 - 它在 boost 的某个地方吗?
我在 博客:
template <typename T, size_t N>
struct array_info<T[N]>
{
typedef T type;
enum { size = N };
};
它是 sizeof(a) / sizeof(a[0])
的优雅替代品。
用于获取数组大小的常用构造肯定应该位于库中的某个位置。我不知道其中之一。谁能告诉我这个功能在标准库中的某个地方和/或在 Boost 中?最好是易于使用且重量轻的形式。
I found the following template on a blog:
template <typename T, size_t N>
struct array_info<T[N]>
{
typedef T type;
enum { size = N };
};
It is an elegant alternative to sizeof(a) / sizeof(a[0])
.
A commonly-used construct for getting the size of an array should surely be somewhere in a library. I'm not aware of one. Can anyone tell me this functionality is in the standard libraries somewhere and/or in Boost? Preferably in an easy-to-use and lightweight form.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我最终自己找到了答案 -
boost::size()
:不过,现在你可能应该使用
std::size()
(自 C++17 起)I eventually found the answer myself -
boost::size()
:Although, these days you should probably use
std::size()
instead (since C++17)在新的 C++ 标准中,标头中的 std::array 具有方法 size(),该方法返回 constexpr,因此在编译时可用。
你应该能够做类似的事情
希望这有帮助......
In the new C++ standard, std::array from the header has the method size(), which returns a constexpr and is therefore available at compile time.
You should be able to to something like
Hope this helps...
C++ 17 支持
std::size()
(在标头
中定义)C++ 17 support
std::size()
(defined in header<iterator>
)如果可能的话,我还会推荐
std::array
或boost::array
如果可能的话。也就是说,您还可以使用 boost::extent 获取数组大小,以及 boost::remove_all_extents 到获取实际类型。在 c++11 中,类型特征也在标准库中提供。
编辑:如果您正在寻找对变量而不是类型进行操作的函数,请尝试以下操作
请参阅 http:// /ideone.com/IOdfp
If possible, I would also recommend
std::array
orboost::array
if possible. That said, you can also use boost::extent to obtain the array sizes, and boost::remove_all_extents to obtain the actual type.In c++11, the type traits are also available in the standard library.
Edit: If your looking for a function that operates on variables, instead of types, try the following
See an example of use at http://ideone.com/IOdfp
您可能需要宏
_countof
。根据 http://www.cplusplus.com/forum/beginner/54241/,它是在
中定义的。但我不确定它是否可以在 Visual C++ 之外使用。无论如何,创建头文件并将定义放在那里并不复杂。
更新:
_countof
是 Microsoft 特定的,但这里有关于其他编译器的讨论:相当于其他编译器中 MSVC 的 _countof?You need perhaps the macro
_countof
. According to http://www.cplusplus.com/forum/beginner/54241/, it's #defined in<cstdio>
. But I am not sure if it's available outside Visual C++.Anyway, it's not complicated to create a header file and put your definition there.
Update:
_countof
is Microsoft-specific, but there is a discussion about other compilers here: Equivalents to MSVC's _countof in other compilers?