I tried to compile the example posted (C++ Service Providers) and failed to VS8 VC9. I have little experience with template.
Any suggestions?
Tanks.
These are the errors :
dictionarystl.cpp(40) : error C2663: ‘std::_Tree<_Traits>::find’ : 2 overloads have no legal conversion for ‘this’ pointer
dictionarystl.cpp(48) : error C2679: binary ‘[‘ : no operator found which takes a right-hand operand of type ‘const type_info *__w64 ‘ (or there is no acceptable conversion)
#include <typeinfo> #include <map> #include <string> using namespace std; class SomeClass { public: virtual ~SomeClass() {} // virtual function to get a v-table }; struct type_info_less { bool operator() (const std::type_info* lhs, const std::type_info* rhs) const { return lhs->before(*rhs) != 0; } }; class TypeMap { typedef map <type_info *, void *, type_info_less> TypenameToObject; TypenameToObject ObjectMap; public: template <typename T> T *Get () const { TypenameToObject::const_iterator iType = ObjectMap.find(&typeid(T)); if (iType == ObjectMap.end()) return NULL; return reinterpret_cast<T *>(iType->second); } template <typename T> void Set(T *value) { ObjectMap[&typeid(T)] = reinterpret_cast<void *>(value); } }; int main() { TypeMap Services; Services.Set<SomeClass>(new SomeClass()); SomeClass *x = Services.Get<SomeClass>(); }
For this code to compile, the following line:
should be: