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.
这篇关于对基类成员数据的派生模板类访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对基类成员数据的派生模板类访问


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09