问题描述
我想让结构
持有枚举
s进行迭代,以及 std :: string
保留其名称以创建菜单项。我使用的是这样的东西:
I would like to have struct
s holding enum
s for iteration, together with std::string
holding their names for creating menu entries. I was using something like this:
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
进行编译:
As I understand, this is preferred to having global variables. It works, but needs instantiation before usage. Now, I found out about this method, which needs --std=C++17
to compile:
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;
}
但是,在内存使用方面,与我以前的方式相比,它的表现如何?怎么做呢?会有什么更好的方法?
But how will this behave, in terms of memory usage, compared to my previous way of doing this? Or is there a wrong way in how I do it? What would be a better way?
推荐答案
您不需要枚举
,当使用 std :: array
时,您可以这样做:
You don't need that enum
when using std::array
. You can do this:
struct S
{
static constexpr std::array<std::string_view, 2> names { "one", "two" };
};
int main()
{
for(auto name: S::names)
std::cout << name << '\n';
}
或者这个:
int main()
{
for(auto n = std::begin(S::names); n != std::end(S::names); ++n)
std::cout << *n << '\n';
}
这与您的第一个示例有很大不同,因为现在您只有一个数组用于 每个 S Sruct S
。以前,每个结构都有自己的数组副本。
This is very different from your first example though because now you only have one array for every sruct S
. Before, every struct has its own copy of the array.
做适合自己需要的事情。每个对象一个数组?还是一个所有对象的数组?
So do what suits your need. One array per object? Or one array for all your objects?
这篇关于用constexpr std :: string_view枚举vs用std :: string实例化的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!