Derived template-class access to base-class member-data(对基类成员数据的派生模板类访问)
问题描述
这个问题是 此线程.
使用以下类定义:
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.
这篇关于对基类成员数据的派生模板类访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对基类成员数据的派生模板类访问
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
