Is it possible to initialize an std::array of unnamed structs?

The below works:

struct
{
    int v;
} vals[] = { {1}, {2} };

Can I do the same thing but instead initialize an std::array ?

Edit since so many people are asking 'why'

There are some very obvious workarounds (listed in the comments), but I only want to use the type once, so I don't really want it added to my current namespace. I could use a tuple or something similar, but having the named values improves clarity. I don't need the c-array value if I am constructing an std::array , so I can't use decltype.

The cleanest solution that I want to do is:

struct
{
    int v;
} std::array vals = { {1}, {2} };

There is an element of academic interest as well - "is this possible in some way I hadn't though of?". Seems like not, so I'll likely use:

struct
{
    int v;
} c_array[] = {};

std::array<std::remove_reference_t<decltype(c_array[0])>, 2> arr = { {1}, {2} };

The reason you can't do:

std::array<struct {int v}, 10> arr;

is because of the following rule from N4140:

§7.1.6/3 [...] A type-specifier-seq shall not define a class or enumeration unless it appears in the type-id of an alias-declaration (7.1.3) that is not the declaration of a template-declaration.

Since a template type argument is specified using a type-id, and a type-id contains a type-specifier-seq, it can't be the definition of a class.

You could use a typedef, but:

§9.1/5 A typedef-name (7.1.3) that names a class type, or a cv-qualified version thereof, is also a class-name. [...]

I would go with the suggestion by TC:

struct { int v; } foo; std::array<decltype(foo), 10> bar = {{{1},{2}}};
链接地址: http://www.djcxy.com/p/83772.html

上一篇: OpenCV找不到我的USB网络摄像头

下一篇: 是否有可能初始化未命名结构的std ::数组?