具有可变参数模板的数据结构

时间:2015-01-18 15:36:07

标签: c++ templates c++11 variadic

我有一个Menu<T>类,其选项是T类型的项目,它可能有Menu<T>类型的子菜单(对嵌套子菜单的深度没有限制)。

template <typename T>
class Menu {
    private:
        class Option {
            const std::string name;
            const T item;
            Menu<T>* submenu;
            Option* next = nullptr;
            friend class Menu<T>;
            Option (const std::string& itemName, const T& t, Menu<T>* menu = nullptr) : name(itemName), item(t), submenu(menu) {}
            ~Option() {if (submenu) delete submenu;}
            inline T choose() const;
            inline void print (int n) const;
        };
        Option* first = nullptr;  // first option in the menu
        Menu<T>* parent = nullptr;
        Option* parentOption = nullptr;
        enum ChoosingType {Normal, Remove};
    public:
        Menu() = default;
        Menu (const Menu<T>&);
        Menu& operator = (const Menu<T>&);
        ~Menu();
        inline void insert (const std::string& itemName, const T& t, Menu<T>* submenu = nullptr, int pos = END_OF_MENU);  
        T choose() const {return chosenItem().first;}
        inline int print() const;
    private:
        inline std::pair<T, int> chosenItem (ChoosingType = Normal) const;
        inline Option* deepCopy (const Option*);
};

我已经测试过它可以正常工作,但我上面的Menu<T>课程不支持其项目与T不同的子菜单。这个额外的功能非常方便,如果说,主菜单有Action作为其选项的类型,然后其中一个选项是&#34;取出武器&#34;,其子菜单最好是以Weapon作为选项,但是就像现在一样,子菜单再次必须有Action作为选项。

我尝试用

进行推广
template <typename T, typename U, typename... Rest>
class Menu {  // Menu with T as its option types.
    private:
        class Option {
            const std::string name;
            const T item;
            Menu<U, Rest...>* submenu;  // Submenu with U as its option types.
            Option* next = nullptr;
            friend class Menu<T, U, Rest...>;
            Option (const std::string& itemName, const T& t, Menu<U, Rest...>* menu = nullptr) : name(itemName), item(t), submenu(menu) {}
            ~Option() {if (submenu) delete submenu;}
            inline T choose() const;
            inline void print (int n) const;
        };
        Option* first = nullptr;
// ....
}

int main() {
    Menu<int, std::string> menu;  // Will not compile.
}

是不正确的,因为Menu<int, std::string> menu;我尝试使用字符串选项的子菜单创建一个简单的int选项菜单,甚至不会编译,因为子菜单的类型为{{1}这与类模板不匹配。它也没有意义,因为Menu<std::string>是从它的Menu<int, std::string>函数返回int,但是进入它的子菜单将返回一个字符串。需要boost :: variant吗?

我只需要有人指出如何开始。我知道这可能看起来属于CodeReview,但是他们只想检查我的代码是否已经有效,但是我在这里尝试概括无法工作(还没有开始),所以我需要这里的专家呼吁如何开始。

更新 根据gmbeard的建议,我使用以下简化代码(真正的菜单类将具有用户将通过输入选择的链接选项列表)。但也有缺点。

choose()

输出:

#include <iostream>
#include <string>

struct Visitor {
    virtual void visit (int&) = 0;
    virtual void visit (std::string&) = 0;
    virtual void visit (char& c) = 0;
};

struct ChooseVisitor : Visitor {
    std::pair<int, bool> chosenInt;
    std::pair<std::string, bool> chosenString;
    std::pair<char, bool> chosenCharacter;
    virtual void visit (int& num) override {
        chosenInt.first = num;
        chosenInt.second = true;
    }
    virtual void visit (std::string& str) override {
        chosenString.first = str;
        chosenString.second = true;
    }
    virtual void visit (char& c) override {
        chosenCharacter.first = c;
        chosenCharacter.second = true;
    }
};

template <typename...> struct Menu;

template <typename T>
struct Menu<T> {
    struct Option {
        T item;
        void accept (ChooseVisitor& visitor) {visitor.visit(item);}
    };
    Option* option;  // Assume only one option for simplicity here.
    ChooseVisitor choose() const {
        ChooseVisitor visitor;
        option->accept(visitor);
        return visitor;
    }
    void insert (const T& t) {option = new Option{t};}
};

// A specialization for the Menu instances that will have submenus.
template <typename T, typename... Rest>
struct Menu<T, Rest...> {  // Menu with T as its options type.
    struct Option {
        T item;
        Menu<Rest...>* submenu;  // Submenu with the first type in Rest... as its options type.
        void accept (ChooseVisitor& visitor) {visitor.visit(item);}
    };
    Option* option;
    ChooseVisitor choose() const {
    // In reality there will be user input, of course.  The user might not choose to enter a submenu,
    // but instead choose from among the options in the current menu.
        ChooseVisitor visitor;
        if (option->submenu)  
            return option->submenu->choose();
        else
            option->accept(visitor);
        return visitor;
    }
    void insert (const T& t, Menu<Rest...>* submenu = nullptr) {option = new Option{t, submenu};}
}; 

int main() {
    Menu<int, std::string, char> menu;
    Menu<std::string, char> submenu;
    Menu<char> subsubmenu;
    subsubmenu.insert('t');
    submenu.insert ("", &subsubmenu);
    menu.insert (0, &submenu);
    const ChooseVisitor visitor = menu.choose();
    if (visitor.chosenInt.second)
        std::cout << "You chose " << visitor.chosenInt.first << ".\n";  // Do whatever with it.
    else if (visitor.chosenString.second)
        std::cout << "You chose " << visitor.chosenString.first << ".\n";  // Do whatever with it.
    else if (visitor.chosenCharacter.second)
        std::cout << "You chose " << visitor.chosenCharacter.first << ".\n";  // Do whatever with it.
}

最大的问题是You chose t. 需要不断更新所有可能的菜单选项类型(最终可能会有数百个数据成员和重载),更不用说可怕的if-checks来获取期望的退货。但是所选项目需要存储,而不仅仅是短期使用。我欢迎改进的想法。

2 个答案:

答案 0 :(得分:1)

一种解决方案是创建Menu的一些部分特化以打开可变参数包。

首先,创建模板类......

// Can be incomplete; only specialized versions will be instantiated...
template<typename... Args> class Menu;

现在,为菜单链的末尾创建一个专门化(没有子菜单)......

template<typename T>
class Menu<T>
{
public:
  // No submenu in this specialization
  using item_type = T;
  std::vector<item_type> items;
  ...
};

最后,为具有子菜单的Menu个实例创建一个专门化...

template<typename Head, typename... Tail>
class Menu<Head, Tail...>
{
public:
  Menu<Tail...> submenu;
  using item_type = Head;
  std::vector<item_type> items;

  ...
};

为简洁起见,这是您的类的简化版本,但如果添加嵌套的Option类,相同的原则仍然适用。

您可以使用类似的技术通过重载非成员函数来递归子菜单......

template<typename T>
void
print_menu(Menu<T> const& menu)
{
  for(auto i : menu.items) {
    std::cout << i << std::endl;
  }
}

template<typename... T>
void
print_menu(Menu<T...> const& menu)
{
  for(auto i : menu.items) {
    std::cout << i << std::endl;
  }
  print_menu(menu.submenu);
}

int
main(int, char*[])
{
  Menu<int, std::string> menu{};
  menu.items.emplace_back(1);
  menu.submenu.items.emplace_back("42");
  print_menu(menu);
  ...
}

更新choose()功能的可能实现可以使用访问者模式。您需要为菜单中包含的每种类型(在这种情况下为operator()int)提供重载std::string的类型...

struct ChooseVisitor
{
  void operator()(std::string const& string_val) const
    { /* Do something when a string value is chosen */ }

  void operator()(int int_val) const
    { /* Do something when an int value is chosen */ }
};

print_menu函数类似,您可以定义几个choose_menu函数重载...

template<typename... Types, typename Visitor>
void
choose_menu(Menu<Types...> const& menu, Visitor const& visitor)
{
  for(auto i : menu.items) {
    if(/* is menu item chosen? */) {
      visitor(i);
      return;
    }
  }
  choose_menu(menu.Submenu, visitor);
}

template<typename Type, typename Visitor>
void
choose_menu(Menu<Type> const& menu, Visitor const& visitor)
{
  for(auto i : menu.items) {
    if(/* is menu item chosen? */) {
      visitor(i);
      return;
    }
  }
}

这样就可以这样使用了......

Menu<int, std::string> menu{};
...
choose_menu(menu, ChooseVisitor{});

要为choose()函数推导出您的想法有点困难,但您应该能够根据大多数情况调整上述内容。

答案 1 :(得分:1)

我有一种轻微的感觉,这里的事情已被过度设计。

正如您所推测的,这是一个使用Boost Variant的版本。

我简化了一些事情。特别是我倾向于初始化列表构造函数,因此您可以简单地以递归方式构造菜单树:

Menu menu = MenuT<int> { 
    { "one",   1 },
    { "two",   2 },
    { "three", 3 },

    { "forty-two", 42, 
            Menu(MenuT<std::string> {
                {"Life, The Universe And Everything", "LtUae"},
                {"Dent", "Arthur", 
                    Menu(MenuT<bool> {
                        {"yes", true},
                        {"no", false},
                    })
                },
            })
    },
};

如您所见,它会在不同级别混合MenuT<int>MenuT<std::string>MenuT<bool>。你可以毫不费力地访问它:

struct simple : boost::static_visitor<>
{
    void operator()(Menu& m) const { boost::apply_visitor(*this, m); }

    template <typename T> void operator()(MenuT<T>& m) const {
        std::cout << "-----------\n";

        for (auto& o : m.options) {
            std::cout << "option '" << o.name << "':\t" << o.item << "\n";
            if (o.submenu)
                (*this)(*o.submenu);
        }
    }
};

打印

-----------
option 'one':   1
option 'two':   2
option 'three': 3
option 'forty-two': 42
-----------
option 'Life, The Universe And Everything': LtUae
option 'Dent':  Arthur
-----------
option 'yes':   true
option 'no':    false

<强> Live On Coliru

#include <string>
#include <vector>
#include <boost/optional.hpp>
#include <boost/variant.hpp>
#include <iostream>

template <typename> struct MenuT;

using Menu = boost::make_recursive_variant < 
        boost::recursive_wrapper<MenuT<int>>,
        boost::recursive_wrapper<MenuT<std::string>>,
        boost::recursive_wrapper<MenuT<bool>>
    >::type;

template <typename T> struct MenuT {
    struct Option {
        std::string           name;
        T                     item;
        boost::optional<Menu> submenu;

        Option(std::string name, T t, boost::optional<Menu> submenu = boost::none)
            : name(name), item(t), submenu(submenu)
        { }

        T choose() const;
        void print(int n) const;
    };

  private:
    template <typename U> friend struct MenuT;
    friend struct visitors;

    std::vector<Option> options;
    //boost::optional<Menu&> parent; // TODO e.g. link_parents_visitor
    enum ChoosingType { Normal, Remove };

  public:
    enum SpecialPosition : size_t { END_OF_MENU = size_t(-1) };

    MenuT() = default;
    MenuT(std::initializer_list<Option> options) : options(options) {}

    void insert(const std::string &itemName, const T &t, boost::optional<Menu> submenu = boost::none, size_t pos = END_OF_MENU) {
        auto it = (pos == END_OF_MENU 
                ? options.end() 
                : std::next(options.begin(), std::min(pos, options.size())));

        options.emplace(it, itemName, t, submenu);
    }

    T choose() const { return chosenItem().first; }
    int print() const;

  private:
    std::pair<T, int> chosenItem(ChoosingType = Normal) const;
};

struct visitors {
    struct simple : boost::static_visitor<>
    {
        void operator()(Menu& m) const { boost::apply_visitor(*this, m); }

        template <typename T> void operator()(MenuT<T>& m) const {
            std::cout << "-----------\n";

            for (auto& o : m.options) {
                std::cout << "option '" << o.name << "':\t" << o.item << "\n";
                if (o.submenu)
                    (*this)(*o.submenu);
            }
        }
    };
}; 

static const visitors::simple demo { };

int main()
{
    Menu menu = MenuT<int> { 
        { "one",   1 },
        { "two",   2 },
        { "three", 3 },

        { "forty-two", 42, 
                Menu(MenuT<std::string> {
                    {"Life, The Universe And Everything", "LtUae"},
                    {"Dent", "Arthur", 
                        Menu(MenuT<bool> {
                            {"yes", true},
                            {"no", false},
                        })
                    },
                })
        },
    };

    std::cout << std::boolalpha;
    demo(menu);
}

<强>说明

  • 值得注意的遗漏是我没有初始化

    boost::optional<Menu&> parent; // TODO e.g. link_parents_visitor
    
  • 我认为你仍然想要简化这一点(我想你可能不希望在一开始就将MenuT和Option分开。你刚才介绍了它试图嵌套不同菜单选项的类型?