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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| #include <map>
#include <string>
#include <iostream>
#include <algorithm>
class Toto
{
const std::map<std::string,std::string> s_map;
protected:
static const std::map<std::string,std::string> init()
{
std::map<std::string,std::string> ret ;
ret["h1"] = "value1" ;
return ret ;
}
public:
template<class T >
Toto(T callable_) : s_map( callable_() ) {}
Toto()
:
// en C++ 0x, avec la délégation de constructeur :
// Toto( &Toto::init ) {}
s_map(init())
{
}
virtual ~Toto() {}
inline const std::map<std::string,std::string>& getMap() { return s_map; }
};
class SuperToto : public Toto
{
private:
static const std::map<std::string,std::string> init()
{
std::map<std::string,std::string> ret = Toto::init();
ret["h2"] = "value2" ;
return ret ;
}
public:
SuperToto():Toto(&SuperToto::init) {}
};
template<class T>
void test()
{
T toto ;
auto toto_map = toto.getMap(); // auto de C++0x
std::for_each(
toto_map.begin(),
toto_map.end(),
[](std::pair<std::string,std::string> const&pair_) // et un p'tit foncteur C++ 0x car cela le vaut bien ;)
{
std::cout<<"["<<pair_.first<<"] = "<<pair_.second<<" ; ";
}
);
std::cout<<"\n";
}
int main()
{
test<Toto>();
test<SuperToto>();
return 0;
} |
Partager