I'm trying to use class as a key of standard map structure.
The usage is like below.
std::map<ClassName, int> someMap; someMap[ StudentClass ] someMap[ TeacherClass ] I'll use this making Template Factory class.
I'm trying to use class as a key of standard map structure.
The usage is like below.
std::map<ClassName, int> someMap; someMap[ StudentClass ] someMap[ TeacherClass ] I'll use this making Template Factory class.
Do you need the class names to be human reaqdable? If not, then you can use typeid and type_info. You can get the string with type_info::name() (details), but note that it is not guaranteed to be anything readable or even unique, for that matter (the type_info object itself, however, is going to be unique). Beyond that, you'll have to either rely on non-portable mechanisms or write your own code for doing this.
[ NUL ], or the same for distinct types, which implies potential robustness / portability issues with using it for this purpose.name provides. To alleviate this you can simply use the type_info itself as the key. It has a before function which provides a natural ordering to the types.It's kind of Microsoft-specific, but I think you could use __uuidof:
std::map<GUID, int> someMap; someMap[__uuidof(StudentClass)] = 1; someMap[__uuidof(TeacherClass)] = 2; someMap[__uuidof(ClassClass)] = 3; There is probably a better way you could do this using a C++ virtual class variable or something like that.
typeid or std::type_info::name?You may use typeid(SomeObject).name(), but it is not portable between compilers. if what you are developing is a library or portable code and you really need a readable "class name", you may write a "meta class" for every class.
template<typename T> class MetaClass{}; class Foobar { //... }; template<> class MetaClass<Foobar> { public: static std::string className() { return "Foobar"; } }; std::map<std::string, int> someMap; someMap[MetaClass<Foobar>::className()] = 0xff; //... If you don't like template, you may implement it in some other way, for example virtual method.