c++staticunnamed-class

Can an unnamed struct be made static?


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

Solution

  • 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.