"Anonymous" struct?

1
2
3
4
struct Something
{ signed int x, y, z; };

std::vector<Something> things;

This works fine. However...
 
std::vector<struct { signed int x, y, z; }> things;

Is there a way to do something like this, without creating a named struct?
No, you can't introduce new types in type specifiers in C++, this isn't C.

you can make std::vector<std::array<int, 3>> things; or std::vector<std::tuple<int, int, int>> things;


... What, can you do it in C?

I'm talking about a struct with various elements, whether they be data types or classes, not std::tuple or std::pair.
in C, you can sneak in struct declarations in any type specifier, although it's not always meaningful, but it compiles: struct {int x;} f(struct {int y;} a);

In C++, if you need a struct, define it as such (at most, you can define objects, pointers/references to, and C-style arrays of it on the same line)
closed account (10X9216C)
Does C++ even support anonymous structures? I think only certain compilers have it as an extra feature.
Unnamed structures, yes of course:
1
2
3
4
5
6
// C++98
struct { int x;} a; 
int main()
{
    a.x = 1;
}


Anonymous structures - no, they are a C11 feature:
1
2
3
4
5
6
7
8
// C11
int main(void)
{
    struct { // unnamed
         struct { int i, j; }; // anonymous
    } v1;
    v1.i = 2;
}
Last edited on
Is there no way to use an unnamed structure in a vector or map?
There is, not not on a single line:

1
2
struct { int x;} a;
std::vector<decltype(a)> v;
Thank you! This is exactly what I was looking for!
Topic archived. No new replies allowed.