【发布时间】:2018-04-01 12:35:08
【问题描述】:
我想让structs 持有enums 进行迭代,同时std::string 持有他们的名字以创建菜单条目。我正在使用这样的东西:
struct S
{
enum E { ONE, TWO, ALL };
std::array<std::string, ALL> names { "one", "two" };
};
int main()
{
S s;
for(int i=s.ONE; i<s.ALL; ++i) // or S::...
std::cout << s.names[i] << '\n';
return 0;
}
据我了解,这比使用全局变量更可取。它可以工作,但需要在使用前进行实例化。现在,我发现了这个方法,需要--std=C++17编译:
struct S
{
enum E { ONE, TWO, ALL };
static constexpr std::array<std::string_view, ALL> names { "one, "two" };
};
int main()
{
for(int i=S::ONE; i<S::ALL, ++i)
std::cout << S::names[i] << '\n';
return 0;
}
但是,与我之前的操作方式相比,在内存使用方面,这将如何表现?还是我的做法有误?有什么更好的方法?
【问题讨论】:
标签: c++ enums static constexpr