【发布时间】:2018-12-03 09:25:52
【问题描述】:
让我考虑一个从基模板类派生的模板类。基类包含一个模板成员。在这种情况下,通常可以使用指针this 从派生类访问基类的成员。然而,当基成员本身就是模板函数时,情况似乎并非如此。
考虑下面的代码
#include <iostream>
template <class T>
struct base {
T x;
base() { x = 10; }
template <unsigned int N>
void increment() { x += N; }
};
template <class T>
struct deriv : public base<T> {
using base<T>::base;
void p()
{
using namespace std;
cout << this->x << endl;
base<int>::increment<1>();
// The following statement causes the compile error:
// expected primary-expression before ‘)’ token
// this->increment<1>();
// Also the following statement gives error
// base<T>::increment<1>();
cout << this->x << endl;
}
};
int main()
{
using namespace std;
base<int> A;
cout << A.x << endl;
A.increment<1>();
cout << A.x << endl;
deriv<int> B;
B.p();
return 0;
}
在main 例程中,模板成员increment 从base 类型的变量中调用。这没有任何问题。
另一方面,deriv 类的成员函数p() 尝试访问从基类继承的模板函数increment。在上面的注释行中使用指针this
this->increment<1>();
给出编译错误
expected primary-expression before ‘)’ token
尝试了一段时间,发现可以通过作用域操作符访问increment函数
base<int>::increment<1>();
然而,这将使用T=int 显式实例化base。如果我想从继承的base<T> 中调用increment 成员,使用泛型T 类作为
base<T>::increment<1>();
我得到与上面相同的错误。
我使用的是 gcc 8.1.1
问题是:为什么使用指针this编译器不能解析继承的成员函数increment?如何从继承的类base 中实例化继承的模板函数increment?
编辑:我添加了另一个无法编译的情况,最好指定问题。
编辑:程序中的小修正,同样的问题。
【问题讨论】: