How to mimic template variable declaration

前端 未结 3 1712
滥情空心
滥情空心 2021-01-21 16:51

I have a basic type Item which depends on an integer template parameter N and class Data which holds instances of Item

相关标签:
3条回答
  • 2021-01-21 17:05

    Following may help:

    struct Data
    {
        std::tuple<std::set<Item<1>>,
                   std::set<Item<2>>,
                   std::set<Item<3>>,
                   std::set<Item<4>>,
                   std::set<Item<5>>> items;
    
        template <int N>
        bool contains(const Item<N>& x) const {
            static_assert(0 < N && N < 6, "N out of range");
            return std::get<N - 1>(items).find(x) != std::get<N - 1>(items).end();
        }
    };
    
    0 讨论(0)
  • 2021-01-21 17:10

    You could, e.g., store a suitable std::tuple<...> and have your contain() function be a template, e.g.:

    template <int... I>
    struct DataImpl {
        std::tuple<std::set<Item<I>>...> data;
        template <int J>
        bool contains(Item<J> const& x) {
            return std::get<J-1>(data).find(x) != std::get<J-1>(data).end();
        }
    };
    using Data = DataImpl<1, 2, 3, 4, 5>;
    
    0 讨论(0)
  • 2021-01-21 17:15

    How about something with a "type list", like so:

    template <unsigned int ...> struct Data;
    
    template <> struct Data<> {};
    
    template <unsigned int N, unsigned int ...Tail>
    struct Data : Data<Tail...>
    {
        std::set<Item<N>> item;
        bool contains(const Item<N> & x) const { return item.find(x) != item.end(); }
    };
    

    Usage:

    Data<2, 8, 19> data;   // contains sets of Item<2>, Item<8> and Item<19>
    
    0 讨论(0)
提交回复
热议问题