I am simplifying things a lot to get a point across. You have a
std::vector<Base*> m_vector;
This basically means: You have a vector of pointers to B
. The actual objects are polymorphic, meaning you don't care what the actual type is as long as they inherit from B
.
Now you want to do something that requires you to know the actual type of the elements.
Thats a contradiction.
The easiest way to solve that contradiction is to give up the second point: Don't care what the actual type is, use only the interface defined in the base class.
One way to do that is to use typeid
. For example:
#include <iostream>
#include <typeinfo>
#include <memory>
#include <vector>
struct Base {
bool same_type(const Base& other) {
return typeid(*this) == typeid(other);
}
virtual ~Base() = default;
};
struct A : Base {};
struct B : Base {};
int main() {
std::vector<std::unique_ptr<Base>> x;
x.emplace_back(std::make_unique<A>());
x.emplace_back(std::make_unique<B>());
x.emplace_back(std::make_unique<B>());
std::cout << "expect 0 : " << (x[0]->same_type(*x[1])) << "\n";
std::cout << "expect 1 : " << (x[1]->same_type(*x[2])) << "\n";
}
For details on typeid
I refer you to https://en.cppreference.com/w/cpp/language/typeid.
As suggested in a comment, you don't actually need to write a Base::same_type()
but you can use typeid
directly.
type()
returns.. - Jesper Juhlclass B: public Base {};
andclass B: public A {};
at the same time. - pptasznitypeid(*a) == typeid(*b)
assuming your types are polymorphic. - johnname
orindex
of your types (for it to work, then need to be polymorphic). - pptaszni