読者です 読者をやめる 読者になる 読者になる

Boost.MultiIndexで基本クラスのメンバをキーにする

C++

BoostML - multi_index with base class member

boost::multi_index::member<base, int, &derived::a>

みたいに指定する。

#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/foreach.hpp>

using namespace boost::multi_index;

struct base {
    int a;

    explicit base(int a_) : a(a_) {}
};

struct derived : public base {
    int b;

    derived(int a_, int b_) : base(a_), b(b_) {}
};

struct idx0 {};

typedef multi_index_container<
    derived,
    indexed_by<
        ordered_unique<
            tag<idx0>, member<base, int, &derived::a>
        >
    >
> container;

int main()
{
    container c;
    c.insert(derived(3, 1));
    c.insert(derived(1, 2));
    c.insert(derived(2, 3));

    BOOST_FOREACH (const derived& d, c)
        std::cout << d.a << "," << d.b << std::endl;
}
1,2
2,3
3,1