这个问题是对 this thread 中提出的问题的进一步插入.
使用以下类定义:
template <class T>
class Foo {
public:
Foo (const foo_arg_t foo_arg) : _foo_arg(foo_arg)
{
/* do something for foo */
}
T Foo_T; // either a TypeA or a TypeB - TBD
foo_arg_t _foo_arg;
};
template <class T>
class Bar : public Foo<T> {
public:
Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
: Foo<T>(bar_arg) // base-class initializer
{
Foo<T>::Foo_T = T(a_arg);
}
Bar (const foo_arg_t bar_arg, const b_arg_t b_arg)
: Foo<T>(bar_arg)
{
Foo<T>::Foo_T = T(b_arg);
}
void BarFunc ();
};
template <class T>
void Bar<T>::BarFunc () {
std::cout << _foo_arg << std::endl; // This doesn't work - compiler error is: error: ‘_foo_arg’ was not declared in this scope
std::cout << Bar<T>::_foo_arg << std::endl; // This works!
}
当访问模板类的基类成员时,似乎我必须始终使用 Bar<T>::_foo_arg
的模板样式语法显式限定成员。 .有没有办法避免这种情况? “using”语句/指令可以在模板类方法中发挥作用以简化代码吗?
编辑:
通过使用 this-> 语法限定变量来解决范围问题。
最佳答案
您可以使用 this->
来明确您指的是类的成员:
void Bar<T>::BarFunc () {
std::cout << this->_foo_arg << std::endl;
}
或者你也可以在方法中使用“using
”:
void Bar<T>::BarFunc () {
using Bar<T>::_foo_arg; // Might not work in g++, IIRC
std::cout << _foo_arg << std::endl;
}
这让编译器清楚地知道成员名称取决于模板参数,以便它在正确的位置搜索该名称的定义。有关更多信息,请参阅 this entry in the C++ Faq Lite .
关于c++ - 派生模板类访问基类成员数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49645682/