问题描述
给出以下代码,编译器将显示一条消息,指出该error: templates may not be ‘virtual’
.有人对如何解决该错误有建议吗?
Given the code below, the compiler is showing a message pointing that error: templates may not be ‘virtual’
. Does anyone have a suggestion on how to solve the bug?
template < class FOO_TYPE>
class CFoo{
public:
...
template < class BAR_TYPE >
virtual void doSomething( const CBar<BAR_TYPE> &); // here's the error
...
virtual ~CFoo();
protected:
MyClass < FOO_TYPE > * m_pClass;
};
template < class FOO_TYPE >
template < class BAR_TYPE >
void CFoo<FOO_TYPE>::doSomething( const CBar<BAR_TYPE> & refBar ){
...
}
推荐答案
了解为什么这是非法的最简单的原因是考虑使用vtable.当然,那只是一种常见的实现,而其他的实现也是允许的.但是C ++中的所有virtual
函数都是经过设计的,因此可以使用vtable来实现.
The easiest reason to see why this is illegal is by considering the vtable. Sure, that's just one common implementation, and others are allowed. But all virtual
functions in C++ are designed such that they can be implemented with a vtable.
现在,在CFoo<int>
的vtable
中有多少个条目?是否有doSomething<float>
的条目?还有doSomething<float*>
?还有doSomething<float**>
吗?诸如此类的模板允许生成无限的功能集.通常这没问题,因为您只使用有限子集,但是对于虚函数,该子集是未知的,因此,vtable必须是无限的.
Now, how many entries are there in the vtable
of CFoo<int>
? Is there an entry for doSomething<float>
? And doSomething<float*>
? And doSomething<float**>
? Templates such as these allow an infinite set of functions to be generated. Usually that's no problem, as you use only a finite subset, but for virtual functions this subset isn't known, and therefore the vtable would need to be infinite.
现在,您可能真的只希望vtable中有一个条目.在这种情况下,您可以将其编写如下:
Now, it's possible that you really wanted only a single entry in the vtable. In that case, you'd write it as follows:
template < class FOO_TYPE, class BAR_TYPE>
class CFoo{
public:
...
virtual void doSomething( const CBar<BAR_TYPE> &); // now OK.
...
virtual ~CFoo();
protected:
MyClass < FOO_TYPE > * m_pClass;
};
这意味着CFoo<int, float>
的vtable将具有一个条目,对于doSomething(float const&)
.
This means that the vtable for CFoo<int, float>
will have one entry, for doSomething(float const&)
.
这篇关于模板可能不是“虚拟"的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!