基本模板类数据成员在派生模板类中不可见? [英] Base template class data members are not visible in derived template class?
问题描述
请考虑以下C ++代码,
Consider the following C++ code,
template <typename Derived>
struct A
{
bool usable_;
};
template <typename Derived>
struct B : A< B<Derived> >
{
void foo()
{
usable_ = false;
}
};
struct C : B<C>
{
void foo()
{
usable_ = true;
}
};
int main()
{
C c;
}
我遇到编译错误:在成员函数 void B< ; Derived> :: foo()
:
I got compilation error: In member function void B<Derived>::foo()
:
template_inherit.cpp:12:error:'useful_'was未在此
范围中声明。
template_inherit.cpp:12: error: 'usable_' was not declared in this scope.
为什么?任何好的修复?
Why is that ? Any good fix ?
推荐答案
这是因为可用_
名称,因此在解析模板时查找,而不是在实例化时查找(当基类已知时)。
That's because usable_
is a non-dependent name, so it is looked up at the time the template is parsed, instead of being looked up at instantiation (when the base class is known).
未限定名称查找将不会查找,而从属名称也不会在依赖基类中查找。您可以使名称可用_
依赖如下,它也将摆脱无限制名称查找
Unqualified name lookup will not lookup and non-dependent names are never looked up in dependent base classes. You can make the name usable_
dependent as follows, which will also get rid of unqualified name lookup
this->usable_ = false;
// equivalent to: A<B>::usable_ = false;
A< B<Derived> >::usable_ = false;
B::usable_ = false;
所有这些都可以工作。或者您可以使用声明在派生类中声明名称
All of these will work. Or you can declare the name in the derived class with a using-declaration
template <typename Derived>
struct B : A< B<Derived> >
{
using A< B<Derived> >::usable_;
void foo()
{
usable_ = false;
}
};
请注意,在 C
问题 - 它只影响 B
。
Note that in C
there will be no problem - it only affects B
.
这篇关于基本模板类数据成员在派生模板类中不可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!