1

When trying to implement menus dynamically in a C++ application of mine without resource files with an interface like the one below, I ran into a problem:

Menu menu_main__ = {
    Menu("File", {
        Menu("Save Configuration", {}),
        Menu("Save Configuration As...", {}),
        Menu(nullptr, {}),
        Menu("Something", {
            Menu("Yay!", {})
        })
    }),
    Keybutter::Menu("Help", {
        Menu("Contents", {}),
        Menu(nullptr, {}),
        Menu("About", {}),
    })
};

Here's are constructors for Menu-class:

Menu(Menu const& menu_) = default;
Menu(Menu&& menu_) = default;
Menu(std::initializer_list<Menu>&& menus_sub__);
Menu(std::nullptr_t const&, std::initializer_list<Menu>&& menus_sub_);
Menu(std::string&& name_, std::initializer_list<Menu>&& menus_sub_);

Now, I figured the only feasible way to implement menu creation is to use recursion. I ended up using lambda recursion inside my Window-class, like this:

std::vector<Menu> menus;

static unsigned int id_menu_sub = 0;

std::function<void (HMENU const&, std::string const&, std::vector<Menu> const&)> create_menus_sub__;
create_menus_sub__ = [&](HMENU const& menu_, std::string const& name_menu_, std::vector<Menu> const& menu_sub_) -> void{
    if(menu_sub_.empty()){
        return;
    }
    else{
        HMENU&& menu_sub__ = CreatePopupMenu();
        for(unsigned int i__ = 0; i__ < menu_sub_.size(); ++i__){
            if(menu_sub_[i__].menus_sub().empty()){
                if(menu_sub_[i__].name.empty()){
                    AppendMenu(menu_sub__, MF_SEPARATOR, ++id_menu_sub, NULL);
                }
                else{
                    AppendMenu(menu_sub__, (menu_sub_[i__].menus_sub().empty()) ? MF_STRING : MF_POPUP | MF_STRING, ++id_menu_sub, menu_sub_[i__].name.c_str());
                }
            }
            else{
                create_menus_sub__(menu_, menu_sub_[i__].name, menu_sub_[i__].menus_sub());
            }
        }
        AppendMenu(menu_, MF_POPUP | MF_STRING, reinterpret_cast<UINT>(menu_sub__), name_menu_.c_str());
    }
};
for(unsigned int i__ = 0; i__ < menus.size(); ++i__){
    HMENU&& menu__ = CreateMenu();
    create_menus_sub__(menu__, menus[i__].name, menus[i__].menus_sub());
    SetMenu(handle_window, menu__);
}

Turned out it did not work as expected. Here is the result:

enter image description here

"Something", instead of being a menu item in "File", is now in wrong location. This was my attempt to create menus dynamically with a good, but somewhat questionable, C++ interface. How can I one use recursion to make menus recursively? How can my code be fixed? I hope I gave enough information.

4

1 回答 1

2

当您递归调用 lambda 时,您传递的是指向menu_而不是的指针menu_sub_,这意味着子菜单被添加到顶层而不是当前子菜单。

顺便说一句,很好地使用了 C++11 功能!:)

于 2013-07-10T20:50:18.393 回答