问题描述
这个问题是 此线程.
使用以下类定义:
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' 语句/指令能否在模板类方法中发挥作用以简化代码?
When accessing the members of the template-class's base-class, it seems like I must always explicitly qualify the members using the template-style syntax of Bar<T>::_foo_arg
. Is there a way to avoid this? Can a 'using' statement/directive come into play in a template class method to simplify the code?
通过使用 this-> 语法限定变量来解决范围问题.
The scope issue is resolved by qualifying the variable with this-> syntax.
推荐答案
您可以使用 this->
来明确您指的是该类的成员:
You can use this->
to make clear that you are referring to a member of the class:
void Bar<T>::BarFunc () {
std::cout << this->_foo_arg << std::endl;
}
您也可以在方法中使用using
":
Alternatively you can also use "using
" in the method:
void Bar<T>::BarFunc () {
using Bar<T>::_foo_arg; // Might not work in g++, IIRC
std::cout << _foo_arg << std::endl;
}
这使编译器清楚地知道成员名称取决于模板参数,以便它在正确的位置搜索该名称的定义.有关详细信息,另请参阅 C++ Faq Lite 中的此条目.
This makes it clear to the compiler that the member name depends on the template parameters so that it searches for the definition of that name in the right places. For more information also see this entry in the C++ Faq Lite.
这篇关于对基类成员数据的派生模板类访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!