我有以下代码,其中模板化的基类是由类似模板化的派生类继承的。编译后,我收到以下错误:
prot.cpp:19:16: error: use of undeclared identifier '_stored_val'; did you mean 'get_stored_val'?
请注意代码中的注释,我可以进行小的更改并让代码编译(和工作)。另外,如果我将TemplatedDerived
声明为继承自TemplatedBase
的具体实例(并在TemplatedDerived
,T -> int
中进行所有必需的关联类型更改),则代码将编译:< / p>
class TemplatedDerived : public TemplatedBase<int>
好像编译器无法将隐式this
识别为派生类的实例。我无法理解为什么会这样,有人请赐教我!
代码:
#include <iostream>
template <typename T>
class TemplatedBase
{
protected:
T _stored_val;
};
template <typename T>
class TemplatedDerived : public TemplatedBase<T>
{
public:
TemplatedDerived() : TemplatedBase<T>() {}
T get_stored_val(void) const
{
/* Compile error occurs on the following line: */
return _stored_val;
/* Both of these work, but what's the difference? */
/* return (*this)._stored_val; */
/* return this->_stored_val; */
/* Additionally, this works. I am somewhat unsurprised, but confused */
/* return TemplatedBase<T>::_stored_val; */
}
};
int main()
{
TemplatedDerived<int> TD;
return TD.get_stored_val();
}