Chr*_*ger 49 c++ c++11 stdarray
鉴于此结构:
struct Foo {
std::array<int, 8> bar;
};
Run Code Online (Sandbox Code Playgroud)
bar如果我没有实例,如何获取数组元素的数量Foo?
Jar*_*d42 81
你可以使用std::tuple_size:
std::tuple_size<decltype(Foo::bar)>::value
Run Code Online (Sandbox Code Playgroud)
sky*_*ack 26
尽管@ Jarod42 得到了很好的答案,但这是另一种可能的解决方案,基于decltype它不使用tuple_size.
它遵循一个在C++ 11中工作的最小的工作示例:
#include<array>
struct Foo {
std::array<int, 8> bar;
};
int main() {
constexpr std::size_t N = decltype(Foo::bar){}.size();
static_assert(N == 8, "!");
}
Run Code Online (Sandbox Code Playgroud)
std::array已经有一个名为constexpr的成员函数size,它返回你要查找的值.
你可以给Foo一个public static constexpr成员.
struct Foo {
static constexpr std::size_t bar_size = 8;
std::array<int, bar_size> bar;
}
Run Code Online (Sandbox Code Playgroud)
现在您知道了bar的大小,Foo::bar_size并且bar_size如果Foo有多个相同大小的数组,您可以更灵活地命名为更具描述性的内容.