4

Does anyone know why the two pointers this and &op2 are first converted to void* before comparing them? (this example is taken from C++ templates: The complete Guide by David Vandevoorde and Nicolai M. Josuttis)

template<typename T>
template<typename T2>
Stack<T>& operator=(const Stack<T2> & op2){
    if ((void*)this==(void*)&op2){
        return *this;
    }
    // ....
}
Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
Dave ddd
  • 117
  • 9
  • 8
    Because two pointers of different types are not comparable? (But that means that the test is silly. There should be two overloads, one for homogeneous types with test and one for mixed types without test.) – Kerrek SB Feb 11 '16 at 15:37
  • Would someone help me read this? This is an operator that allows assigning a Stack to a Stack, so I could assign a Stack to a Stack? And the check is to see if the Stack already is the same Stack? – Moby Disk Feb 11 '16 at 16:30
  • 1
    @MobyDisk, that is a possibility, only if a `Dog` can be assigned to a `Cat`. It will work for types that can be converted implicitly. For instance, you will be able to assign a `Stack` to a `Stack`. – R Sahu Feb 11 '16 at 16:38
  • @RSahu Are you sure? http://stackoverflow.com/questions/4807643/container-covariance-in-c We don't know much about this Stack class, but STL containers do not support what you described. – Moby Disk Feb 11 '16 at 17:45

1 Answers1

3

As mentioned by @KerrekSB in a comment, this is poor coding style.

What the author is trying to do is avoid compile time warning for comparing pointers of different types, such as a pointer of type Stack<int>* and a pointer of type Stack<double>*.

It could be easily avoided by using overloads.

// Assign an object of the same type.
template<typename T>
Stack<T>& operator=(const Stack<T> & op2){
    if (this == &op2){
        return *this;
    }
    // ....
}

// Assign an object of a different type.
template<typename T>
template<typename T2>
Stack<T>& operator=(const Stack<T2> & op2){

    // For objects of different types, this check is not necessary
    // at all. It will always be false.
    // if ((void*)this==(void*)&op2){
    //     return *this;
    /// }

    // ....
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 1
    For C, I found that it holds even more: The standard does not require two pointers to different object types to be comparable. See http://c0x.coding-guidelines.com/6.5.9.pdf, page 5-6. Is this also applicable to C++, i.e. > Because the operands need not refer to the same objects, it is necessary to compare all the information > represented in a pointer value (e.g., segment and offset in a segmented architecture). [...] – overseas Feb 11 '16 at 16:22