Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 226
Lars Avatar asked Mar 09 '11 04:03

Lars


1 Answers

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.

like image 59
Ben Voigt Avatar answered Oct 04 '22 01:10

Ben Voigt