Initialising a struct that contains a vector of itself

前端 未结 3 1866
余生分开走
余生分开走 2020-12-19 01:00

I have a menu system that I want to initialise from constant data. A MenuItem can contain, as a sub-menu, a vector of MenuItems. But it only works

3条回答
  •  庸人自扰
    2020-12-19 01:59

    GMan is correct in his comment: in the declaration of S::v in your code, S is still incomplete. A type must be complete to be usable as the value type in an STL container. For more information see Matt Austern's article "The Standard Librarian: Containers of Incomplete Types."

    If you were to switch to a container that is usable with an incomplete type, then your code is fine. For example, given the following:

    #include 
    
    template 
    struct Container
    {
        Container() { }
        Container(std::initializer_list) { }
    };
    
    struct S { Container v; };
    

    then your original initialization should work fine:

    S s3 = { { { } } } ;
    

    This would work too:

    S s4 = { { { { { { { { { { { { { { { { /*zomg*/ } } } } } } } } } } } } } } } };
    

提交回复
热议问题