I'm writing a simple program which saves all its data to xml file.
I've got a few different classes to save in it, but no idea how to differ them.
I could another string but that won't do in few cases.
Help.
Might typeid(sometype variable) be the function you are looking for?
1 2 3 4 5 6 7 8 9 10 11 12
#include <typeinfo>
#include <iostream>
class someClass { };
int main(int argc, char* argv[]) {
int a;
someClass b;
std::cout<<"a is of type: "<<typeid(a).name()<<std::endl; // Output 'a is of type int'
std::cout<<"b is of type: "<<typeid(b).name()<<std::endl; // Output 'b is of type someClass'
return 0;
}
Don't use typeid for that. It was reluctantly added to the language and when used, should only be used internally. There is no guarantee that the string returned will be the same across vendors or environments or accross compiler versions ...
If fact, I'd go as far to say that if you're relying on it, you're design is sub-optimal.
Polymorphism doesn't apply for primitive types, but you could use specialized templates although that could get cumbersome writing a template for every primitive types.
I haven't tested this but in theory, couldn't you check primitive types simply by comparing the type_info returned by the typeid operator?
Ciao, Imi.
PS: If your compiler doen't have "static_assert" yet, just don't implement name() alltogether. Error message is not that pretty, but you still get compile errors for missing types.
if (typeid(a) == typeid(int()))
Really BAD advice.
You should provide a mechanism where each type streams itself into a useable format. One example is the way the iostream library can be used to stream types a textual representation. Do the same for your XML.
You should provide a mechanism where each type streams itself into a useable format. One example is the way the iostream library can be used to stream types a textual representation. Do the same for your XML.
Using typeid() itself is safe in in comparing it to other typeid's during the same programm execution. It's the .name() where there is no guarantee about at all.
But even for typeid, you should not store it in some file. Just think of it as some type identifier that changes every time you run your code. ;-)
The most place where typeid is used is in such if-comparison to check for the dynamic type of a base class:
1 2 3 4 5 6 7
void f (myclass* p)
{
// do we really have a myclass? Maybe I got a subclass of myclass?
// I really want to have myclass here, so lets check:
if (typeid(*p) == typeid(myclass))
...
}
However, this code has most probably serious design problems. Most of the time you just should not have to care whether you got myclass* or a subclass of it. That's what inheritance is about, isn't it?
The same goes for integral types along a similar line of reasoning. typeid(int) != typeid(long), but most code should just not care whether he got a long when he wanted an int - as all you can do with ints you can also do with longs.. roughly said..