开发者

Checking if caller and parameter are the same

For example I 开发者_运维百科have four classes like:

class A;

class B{
protected:
    void check(const A &a); 
};

class C : public A, public B;
class D : public B;

Now I would like to write check function that does nothing if the caller and parameter are the same:

void B::check(const A &a){
   if(*this != a){
      //do something
   }
   else{
      //do nothing
   }
}

However this won't compile as class B doesn't know anything about class C, which will one day call B's function check on itself. It would be easy to cast this into A, but that would give an error if one day class D would call that check as it has nothing to do with A. How is such thing done then?

Edit: I might had to mention that class C and D will have interface for calling that check which is not avalible outside these classes, but it'll do nothing more than just pass parameter to inner function


This would work if you add a virtual destructor to A:

void B::check(const A &a)
{
    if (dynamic_cast<const B*>(&a) == this)
    {
        std::cout << "same object" << std::endl;
    }
}


if(*this != a)

Check is meaningless because this(class B) will never be same as type of class A because both are unrelated classes.

It is not clear what you want to do, but if you want your Base class pointer to be pointing to your derived class object then there must be a inheritance(is-a) relationship between them.


There's only one possible escape hatch here. If both A and B have a virtual function, then you can dynamic_cast both this and &a. And per 5.2.7/7 "If T is “pointer to cv void,” then the result is a pointer to the most derived object pointed to by v."

Therefore, this code works:

void B::check(const A &a){
   if(dynamic_cast<void const*>(const_cast<B const>(this) != dynamic_cast<void const*>(&a)) {
      //do something
   } ...

Nothing else gets you a pointer to the most derived object without knowing that type.


You probably want to check whether the instances are the same:

void B::check(const A &a){
   if(this != &a){
      //do something
   }
   else{
      //do nothing
   }
}

Comparing the content of different classes doesn't make much sense to me.


You can do something like this:

void check(const A &a){
   if((void*)this != (void*)&a){
      //do something
   }
   else{
      //do nothing
   }
}


Is this what you're looking for — to check whether this and a are both parts of the same object of type C?

void B::check(A &a)
{
    std::cout << (static_cast<C*>(this) != static_cast<C*>(&a)) << std::endl;
}

int main()
{
    C c;
    D d;
    A& a1 = c;
    A a2;
    boolalpha(std::cout);
    c.check(a1); // false
    c.check(a2); // true
    d.check(a1); // true
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜