Reputation: 283
I'm having a really hard time finding information about these kind of stuff! :(
I'm confused why this isn't working:
vector<B*> b;
vector<C*> c;
(B and C are subclasses of A)
(both are also initialized and contain elements etc etc...)
template <class First, class Second>
bool func(vector<First*>* vector1, vector<Second*>* vector2)
return vector1 == vector2;
When compiling this returns:
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
I don't see why this wouldn't work, pointers hold addresses yeah? So why don't it just compare if the two vector pointers... point to the same address(-es)?
Upvotes: 6
Views: 6574
Reputation: 2713
Your two vectors are different types and you cannot compare them.
If you want to check that you do not call func(b, b) then you can try:
template <typename T> bool func(vector<T> const & a, vector<T> const & b)
{
if (&a == &b) return false;
// do stuff
return true;
}
Unless you are doing something very strange then the pointers to two vectors of a different types will not be equal. If you try and call func with two vectors of a different type then you will get a compiler error.
Upvotes: 4
Reputation: 67723
Here's a simple example where what you're asking for won't work.
struct A{ int i; };
struct OhNoes { double d; };
struct B: public A {};
struct C: public OhNoes, public B {};
So here, B and C are both subclasses of A.
However, an instance of C
is unlikely to have the same address as its B
subobject.
That is, this:
C c;
B *b = &c; // valid upcast
assert(static_cast<void*>(b) == static_cast<void *>(&c));
will fail.
Upvotes: 8