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

别说谁变了你拦得住时间么 提交于 2019-12-10 14:23:44

问题


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?


回答1:


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.




回答2:


I believe you should use:

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

or:

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



来源:https://stackoverflow.com/questions/5241481/how-to-call-a-template-member-function-in-a-template-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!