0

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.

2

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

"not guaranteed to be anything readable" understates the issue a little - it is allowed to be simply [ NUL ], or the same for distinct types, which implies potential robustness / portability issues with using it for this purpose.
Tony is correct, there is no requirement on what 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.
2

The best bet would be to use, typeid(). It will give you the uniqueness across classes. However, you cannot retrieve the class type from typeid automatically.

Comments

1

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.

1 Comment

Why not use typeid or std::type_info::name?
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.