Derived template-class access to base-class member-data

Shamster picture Shamster · Jul 13, 2009 · Viewed 47.4k times · Source

This question is a furtherance of the one asked in this thread.

Using the following class definitions:

template <class T>
class Foo {

public:
    Foo (const foo_arg_t foo_arg) : _foo_arg(foo_arg)
    {
        /* do something for foo */
    }
    T Foo_T;        // either a TypeA or a TypeB - TBD
    foo_arg_t _foo_arg;
};

template <class T>
class Bar : public Foo<T> {
public:
    Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
    : Foo<T>(bar_arg)   // base-class initializer
    {

        Foo<T>::Foo_T = T(a_arg);
    }

    Bar (const foo_arg_t bar_arg, const b_arg_t b_arg)
    : Foo<T>(bar_arg)
    {
        Foo<T>::Foo_T = T(b_arg);
    }

    void BarFunc ();

};

template <class T>
void Bar<T>::BarFunc () {
    std::cout << _foo_arg << std::endl;   // This doesn't work - compiler error is: error: ‘_foo_arg’ was not declared in this scope
    std::cout << Bar<T>::_foo_arg << std::endl;   // This works!
}

When accessing the members of the template-class's base-class, it seems like I must always explicitly qualify the members using the template-style syntax of Bar<T>::_foo_arg. Is there a way to avoid this? Can a 'using' statement/directive come into play in a template class method to simplify the code?

Edit:

The scope issue is resolved by qualifying the variable with this-> syntax.

Answer

sth picture sth · Jul 13, 2009

You can use this-> to make clear that you are referring to a member of the class:

void Bar<T>::BarFunc () {
    std::cout << this->_foo_arg << std::endl;
}

Alternatively you can also use "using" in the method:

void Bar<T>::BarFunc () {
    using Bar<T>::_foo_arg;             // Might not work in g++, IIRC
    std::cout << _foo_arg << std::endl;
}

This makes it clear to the compiler that the member name depends on the template parameters so that it searches for the definition of that name in the right places. For more information also see this entry in the C++ Faq Lite.