如何在模板基类中调用模板成员函数? [英] How to call a template member function in a template base class?
问题描述
在基类中调用非模板成员函数时,可以使用 using
将其名称导入派生类,然后使用它.基类中的模板成员函数也可以吗?
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?
仅使用 using
无效(使用g ++-snapshot-20110219 -std = c ++ 0x):
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>();
}
我知道像
A<T>::template f<T2>();
可以很好地工作,但是问题是:是否可以没有使用简单的使用声明(就像 f
不是模板函数的情况一样)?
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?
推荐答案
这可行(双关语意): this-> template f< T2>();
this works (pun intended): this->template f<T2>();
也是
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>();
}
};
为什么 using
在与模板相关的模板功能上不起作用很简单-语法不允许在这种情况下使用必需的关键字.
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.
这篇关于如何在模板基类中调用模板成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!