Reputation: 11180
I already figured out to use polymorphism and have the list store the pointer to the baseClass, but after successfully placing it there, I would like to know what class the object was originally. I am using templates for the classes, and wanted to have an another field which would be an enum of basic types.
Now the question: is there a way to check (during runtime or during compilation) an
(if T == int)
field = INT
I though maybe something with the preprocessor but I'm not familiar with that.
Upvotes: 0
Views: 278
Reputation: 20063
What you are probably looking for is known as type traits. They allow you to determine and act on the attributes of a specific type. You could start with std::is_integral()
and std::is_floating_point()
and build from there depending on your requirements.
enum Type
{
Unknown,
Integral,
Float
};
....
Type field = Unknown;
if(std::is_integral<T>::value)
{
field = Integral;
}
else if(std::is_floating_point<T>::value)
{
field = Float;
}
Upvotes: 1
Reputation: 57774
The C++ preprocessor knows nothing about C++. It is a generic symbol manipulator which can be used with most any programming language, or for that matter, any text processing application, such as a feature of word or equation layout processing.
You might look into the typeid operator as one way to build such a mechanism, though heed the Misuses of RTTI section further down on that page.
Upvotes: 0
Reputation: 13713
The whole idea behind polymorphism is to hide the specific implementation making it transparent in your program flow. Using type of class as an indicator will make your code bloat with if
statements and will be harder to maintain.
I suggest you reconsider your design and make an abstract class with the intended behavior methods and use this class type as the list objects type. Than for each object call the interface method (which was declared in the abstract class and implemented in the deriving classes)
Upvotes: 4
Reputation: 13529
You can use operator typeid
.
For example, if T
is a pointer to a base class:
if (typeid(SomeDerivedClass) == typeid(*T))
...
(It is somewhat unclear for me why you speak about int
in connection with polymorphism. int
cannot be derived from.)
Upvotes: 1