Cha*_*l72 4 c++ templates using
我知道基类模板的成员名称隐藏在派生类的范围内,因此必须使用this->foo或访问Base<T>::foo.但是,我记得C++还允许您使用using关键字,它可以在派生类函数中派上用场,该函数经常访问基类变量.所以,为了避免在this->任何地方混乱功能,我想使用using关键字.
我知道我以前做过这个,但无论出于什么原因我现在都无法上班.我可能只是做了一些愚蠢的事情,但以下代码无法编译:
template <class T>
struct Base
{
int x;
};
template <class T>
struct Derived : public Base<T>
{
void dosomething()
{
using Base<T>::x; // gives compiler error
x = 0;
}
};
int main()
{
Derived<int> d;
}
Run Code Online (Sandbox Code Playgroud)
错误(使用GCC 4.3)是: error: ‘Base<T>’ is not a namespace
为什么这不起作用?
它不起作用,因为C++语言没有这样的功能,从来没有.类成员的using声明必须是成员声明.这意味着您只能在类范围内使用,但绝不能在本地范围内使用.这一切都与模板完全无关.
换句话说,您可以将using声明放入类范围
struct Derived : public Base<T> {
...
using Base<T>::x;
...
};
Run Code Online (Sandbox Code Playgroud)
但是你不能把它放在一个函数里面.
名称空间成员的使用声明可以放在本地范围内,但类成员的使用声明不能.这就是错误消息抱怨Base<T>不是命名空间的原因.