Derived template-class access to base-class member-data: for dependent name

98 views Asked by At

In the following long list of codes, please look for three places:

  1. // "this->" can be omitted before first data[0]

and

  1. // Compile error, if "this->" is omitted before first data[0]

and

  1. // likewise, "this->" is required.

I don't know why sometimes "this->" can be omitted, and sometime can't.

The compile error is: main.cpp:19:3: error: 'data' was not declared in this scope

Is it just a compiler bug? My compiler is GCC v4.8.1 and v4.8.2. Thanks. BTW, QtCreator's default intelli-sense, in fact, can recognize 'data[0]' without "this->" in all three places.

Here's the code list:

template <typename T>
struct Vec3_
{
    T data[3];
    inline Vec3_<T> & operator =(const Vec3_<T> & rhs) {
        if (this != &rhs) {
            data[0] = rhs.data[0];  // "this->" can be omitted before first data[0]
            data[1] = rhs.data[1];
            data[2] = rhs.data[2];
        }
        return *this;
    }
};

template <typename T>
struct Vec3i_: Vec3_<T>
{
    inline Vec3i_<T> & operator ^=(const Vec3i_<T> & rhs) {
        data[0] ^= rhs.data[0];     // Compile error, if "this->" is omitted before first data[0]
        this->data[1] ^= rhs.data[1];
        this->data[2] ^= rhs.data[2];
        return *this;
    }
    inline Vec3i_<T> operator ^(const Vec3i_<T> & rhs) const {
        Vec3i_<T> tmp;
        tmp[0] = this->data[0] ^ rhs.data[0];  // likewise, "this->" is required.
        tmp[1] = this->data[1] ^ rhs.data[1];
        tmp[2] = this->data[2] ^ rhs.data[2];
        return tmp;
    }
};

Vec3i_<int> A;

int main(int, char**) { return 0; }

== update ==

Since someone has pointed out a very similar question (may possibly a duplicate) and answers, and the title of that question is even descriptive, I changed my title similar to that one (except the parameter dependency difference)

Yet after reading the answers to that question, I am still confused. The answers pointed to an FAQ [link here] saying that if a variable is a nondependent name, the compiler will not search for the name in the base template class. However, in this example, the variable (data) is a dependent name, since it is of type T, and T is the template variable.

I am still open for answers.

0

There are 0 answers