模板基类继承还有其他解决方法吗?
此代码在 GNU 编译器中产生错误:
class A
{
public:
int X;
};
template<class T>
class Foo : public T
{
public:
void doStuff();
};
template<class T>
void Foo<T>::doStuff()
{
X++;
}
已经有 为什么这是一个错误的答案。我想知道是否有另一种方法可以解决此错误,而不是
T::X
每次我想引用 X 成员时都使用它。我尝试了这个:
template<class T>
void Foo<T>::doStuff()
{
using T::X;
X++;
}
但是 GCC 给出了一个错误:“不允许使用类限定名称”
This code produces an error in the GNU compiler:
class A
{
public:
int X;
};
template<class T>
class Foo : public T
{
public:
void doStuff();
};
template<class T>
void Foo<T>::doStuff()
{
X++;
}
There is already an answer for why this is an error. I would like to know if there is another way of working around this error rather than using
T::X
every time I want to reference the X member. I tried this:
template<class T>
void Foo<T>::doStuff()
{
using T::X;
X++;
}
But GCC gives an error: "a class-qualified name is not allowed"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 T::X
应该可以。如果出现错误,则说明您的代码存在其他问题,或者一定是编译器错误。查看您自己:http://www.ideone.com/MI9fM您可以使用
this
指针,如这为编译器提供了在何处查找符号
X
的提示。演示:http://www.ideone.com/NIucO
您也可以这样做:
演示:http://www.ideone.com/PswvG
using T::X
should work. If it gives error, there is some other problem with your code, or it must be compiler bug. See yourself : http://www.ideone.com/MI9fMYou may use
this
pointer, asThis gives compiler a hint where to look for the symbol
X
.Demo: http://www.ideone.com/NIucO
You can also do this:
Demo : http://www.ideone.com/PswvG
这也可行:
这会告诉编译器,因为它认为 X 不是派生类的成员,所以它必须来自模板库,无需担心。
This would also work:
That would tell the compiler than since it sees X is not a member of the derived class, it has to come from the template base and there is no need to worry about it.
也许这会起作用?只是猜测:
这将创建一个可以在代码块中使用的别名,类似于您尝试过但不起作用的
using T::X
。Maybe this will work? Just guessing:
This will create an alias that can be used within a block of code, similarly to the
using T::X
you tried that didn't work.