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
| #include <map>
#include <string>
#include <iostream>
template <typename Key,typename Value> class Map : public std::map<Key,Value> // J'enrichit la classe std::map mais je reste "générique"
{
public:
using typename std::map<Key,Value>::const_iterator ; // <-- tout un tas de using dont j'aimerais bien me passer
using std::map<Key,Value>::operator[] ;
using std::map<Key,Value>::begin ;
using std::map<Key,Value>::find ;
using std::map<Key,Value>::end ;
Value get ( const Key & key , const Value & def ) const
{
const_iterator f = find( key ) ;
return (f == end()) ? def : f->second ;
}
friend std::ostream & operator<< ( std::ostream & out , const Map<Key,Value> & self )
{
for ( const_iterator i = self.begin() ; i != self.end() ; ++i )
out << " " << i->first << ":" << i->second ;
return out ;
}
};
class Dictionary : public Map<std::string,std::string> // Je spécialise ma classe pour des besoins + spécifiques
{
public:
Dictionary & add ( const std::string & key , const std::string & value ) { (*this)[key] = value ; return *this ;}
};
int main ()
{
Dictionary d ;
d.add("0","zero").add("1","one") ;
d["spam"] = "eggs" ; // ici, sans le using operator[], ça ne compile pas
std::cout << d << " / 2:" << d.get("2","???") << std::endl ;
} |
Partager