Lars
Lars

Reputation: 2636

How to call a template member function in a template base class?

When calling a non-templated member function in a base class one can import its name with using into the derived class and then use it. Is this also possible for template member functions in a base class?

Just with using it does not work (with g++-snapshot-20110219 -std=c++0x):

template <typename T>
struct A {
  template <typename T2> void f() {  }
};

template <typename T>
struct B : A<T> {
  using A<T>::f;

  template <typename T2> void g() {
    // g++ throws an error for the following line: expected primary expression before `>`
    f<T2>();
  }
};

int main() {
  B<float> b;
  b.g<int>();
}

I know that prefixing the base class explicitly as in

    A<T>::template f<T2>();

works fine, but the question is: is it possible without and with a simple using declaration (just as it does for the case where f is not a template function)?

In case this is not possible, does anyone know why?

Upvotes: 5

Views: 7947

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283883

this works (pun intended): this->template f<T2>();

So does

template <typename T>
struct B : A<T> {
  template <typename T2> void f()
  { return A<T>::template f<T2>(); }

  template <typename T2> void g() {
    f<T2>();
  }
};

Why using doesn't work on template-dependent template functions is quite simple -- the grammar doesn't allow for the required keywords in that context.

Upvotes: 10

eric zhu
eric zhu

Reputation: 51

I believe you should use:

this->A<T>::template f<T2>();

or:

this->B::template f<T2>();

Upvotes: 1

Related Questions