在基类中调用非模板化成员函数时,可以将其名称通过 using
导入到派生类中,然后使用它。 这是否也适用于基类中的模板成员函数?
仅使用 using
它不起作用(使用 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>();
工作正常,但问题是:是否可以不使用和使用简单的 using 声明(就像 f
不是模板函数的情况一样)?
如果这是不可能的,有人知道为什么吗?
最佳答案
这个作品(双关语):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
不适用于依赖于模板的模板函数非常简单——语法不允许在该上下文中使用必需的关键字。
关于c++ - 如何在模板基类中调用模板成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5241481/