Initialising a struct that contains a vector of itself

前端 未结 3 624
悲哀的现实
悲哀的现实 2020-12-19 01:15

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:55

    boost::optional and boost::recursive_wrapper look useful for this

    struct S { // one brace
        boost::optional< // another brace
          boost::recursive_wrapper< // another brace
            std::vector< // another brace
              S
            >
          >
        > v; 
    };
    

    You need 4 braces for every submenu you add. Brace elision does not happen when constructor calls are involved. For example

    S m{{{{ 
      {{{{ }}}}, 
      {{{{ 
        {{{{ }}}}, 
        {{{{ }}}} 
      }}}} 
    }}}}; 
    

    Honestly, using constructors look more readable

    struct S {
        // this one is not really required by C++0x, but some GCC versions
        // require it.
        S(char const *s)
        :v(s) { } 
    
        S(std::string const& s)
        :v(s) { }
    
        S(std::initialize_list s)
        :v(std::vector(s)) { } 
    
        boost::variant<
          std::string,
          boost::recursive_wrapper<
            std::vector<
              S
            >
          >
        > v; 
    };
    

    Now it simplifies to

    S s{ 
      "S1", 
      {
        "SS1",
        "SS2",
        { "SSS1", "SSS2" }
      }
    };
    

提交回复
热议问题