1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| template<class Derived>
CBase {
virtual void foo() const = 0;
};
CDerivedA : public CBase <CDerivedA> {
virtual void foo() const { cout << "je suis A"; }
void foo2() const { cout << "je suis encore A"; }
};
CDerivedB : public CBase <CDerivedB> {
virtual void foo() const { cout << "je suis B"; }
void foo2() const { cout << "je suis encore B"; }
};
struct output : public boost::static_visitor<>
{
void operator()(CBase <CDerivedA> const& d) const { d.foo2(); }
void operator()(CBase <CDerivedB> const& d) const { d.foo2(); }
};
typedef boost::variant< CDerivedA, CDerivedB > cbase_t;
map<int, cbase_t> une_map;
une_map.insert(make_pair(0, CDerivedA()));
une_map.insert(make_pair(1, CDerivedB()));
// appelle de foo()
BOOST_FOREACH(const map<int, cbase_t>::value_type& une_paire, une_map)
{
une_paire.second.foo();
}
// appelle de foo2()
BOOST_FOREACH(const map<int, cbase_t>::value_type& une_paire, une_map)
{
boost::apply_visitor(output(), une_paire.second);
}
// Récupérer spécifiquement le type
CDerivedA value = boost::get<CDerivedA>(une_map[0]); |
Partager