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
|
#include <iostream>
#include <map>
#include <boost/function.hpp>
template < class Key, class Fct > class SWITCH
{
public:
void Process(const Key& k) const
{
typename std::map<Key,Fct>::const_iterator it=m_map.find(k);
if(it!=m_map.end())
it->second(k); //on pourrait rajouter un else pour traiter le default
}
void Add(const Key& k,Fct t) //aucune gestion des doublons au niveau des clés, à toi de voir et d'adapter selon tes besoins
{
m_map[k]=t;
}
private:
std::map<Key,Fct> m_map;
};
void bar(int){std::cout<<"bar"<<std::endl;}
void foo(int){std::cout<<"foo"<<std::endl;}
int main(int argc, char const *argv[])
{
SWITCH<int,boost::function<void (int)> > s;
s.Add(0,foo);
s.Add(1,bar);
s.Process(0);
s.Process(2);
return 0;
} |
Partager