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
|
#include <string>
#include <map>
#include <iostream>
template<typename keyClass, typename valueClass>
class PropertiesWrapper{
public:
PropertiesWrapper(std::map<keyClass, valueClass>&);
void setProperty(keyClass& key, valueClass& value);
private:
std::map<keyClass, valueClass>& test;
};
template<class keyClass, class valueClass>
PropertiesWrapper<keyClass, valueClass>::
PropertiesWrapper(std::map<keyClass, valueClass>& sm) : test(sm) { }
template<class keyClass, class valueClass>
void PropertiesWrapper<keyClass, valueClass>
::setProperty(keyClass& key, valueClass& value) {
typedef std::map<keyClass, valueClass> KeyToValue;
typedef typename KeyToValue::iterator Iterator;
typedef std::pair<Iterator, bool> Pair;
Pair success = test.insert(std::pair<keyClass, valueClass>(key, value));
if(success.second){
std::cout << "Success !!!" << std::endl;
std::pair<keyClass, valueClass> py = *success.first;
std::cout << "key is " << py.first.getVal() << std::endl;
std::cout << "value is " << py.second.getVal() << std::endl;
}
}
class keyClass {
std::string s;
public:
keyClass(std::string x) : s(x) {}
std::string getVal() const { return s;}
bool operator< (const keyClass& rhs ) const { // needed for compare key in the map
return s < rhs.s;
}
};
class valueClass {
int i;
public:
valueClass(int x) : i(x) {}
int getVal() const { return i; }
};
int main() {
keyClass key1("key1");
valueClass value1(100);
keyClass key2("key2");
valueClass value2(200);
std::map<keyClass, valueClass> sm;
PropertiesWrapper<keyClass, valueClass> pw(sm);
pw.setProperty(key1,value1);
pw.setProperty(key2,value2);
return 0;
}
| |