What is this crazy C++11 syntax ==> struct : bar {} foo {};?

后端 未结 2 491
感动是毒
感动是毒 2020-12-07 07:17

What could this possibly mean in C++11?

struct : bar {} foo {};
2条回答
  •  温柔的废话
    2020-12-07 07:34

    First, we'll take a bog-standard abstract UDT (User-Defined Type):

    struct foo { virtual void f() = 0; }; // normal abstract type
    foo obj;
    // error: cannot declare variable 'obj' to be of abstract type 'foo'
    

    Let's also recall that we can instantiate the UDT at the same time that we define it:

    struct foo { foo() { cout << "!"; } };          // just a definition
    
    struct foo { foo() { cout << "!"; } } instance; // so much more
    // Output: "!"
    

    Let's combine the examples, and recall that we can define a UDT that has no name:

    struct { virtual void f() = 0; } instance; // unnamed abstract type
    // error: cannot declare variable 'instance' to be of abstract type ''
    

    We don't need the proof about the anonymous UDT any more, so we can lose the pure virtual function. Also renaming instance to foo, we're left with:

    struct {} foo;
    

    Getting close.


    Now, what if this anonymous UDT were to derive from some base?

    struct bar {};       // base UDT
    struct : bar {} foo; // anonymous derived UDT, and instance thereof
    

    Finally, C++11 introduces extended initialisers, such that we can do confusing things like this:

    int x{0};
    

    And this:

    int x{};
    

    And, finally, this:

    struct : bar {} foo {};
    

    This is an unnamed struct deriving from bar, instantiated as foo with a blank initializer.

提交回复
热议问题