Can an unnamed struct be made static?

808 Views Asked by At

Can you make an unnamed struct a static member of a class?

struct Foo
{
    struct namedStruct
    {
        int memb1, memb2;
    };
    static namedStruct namedStructObj;
    struct
    {
        int memb1, memb2;
    } unnamedStructObj;
};

Foo::namedStruct Foo::namedStructObj;
// The unnamed type doesn't seem to have a type you can write
2

There are 2 best solutions below

0
Mário Feroldi On BEST ANSWER

Yes, it's possible:

struct Foo
{
    struct
    {
        int memb1, memb2;
    } static unnamedStructObj;
};

decltype(Foo::unnamedStructObj) Foo::unnamedStructObj;

Here, as you don't have any way to reference the unnamed struct, using decltype(Foo::unnamedStructObj) makes it possible to retrieve the type of Foo::unnamedStructObj, so you can write the definition.

0
llllllllll On

You can do it with the help of decltype():

struct Foo
{
    struct namedStruct
    {
        int memb1, memb2;
    };
    static namedStruct namedStructObj;
    static struct
    {
        int memb1, memb2;
    } unnamedStructObj;
};

Foo::namedStruct Foo::namedStructObj;
decltype(Foo::unnamedStructObj) Foo::unnamedStructObj;