我有一些代码可以在VS2008中运行,但不能在G ++中运行:
struct IIterationFunctor
{
virtual bool operator()( SStateInfo& rStateInfo ) = 0;
virtual ~IIterationFunctor() { }
};
struct SNumItemsFunctor : public IIterationFunctor
{
SNumItemsFunctor (uint8& nNumItems, uint8 nItemType )
: m_nNumItems (nNumItems)
, m_nItemType (nItemType)
{
m_nNumItems = 0;
}
virtual bool operator() ( SStateInfo& rStateInfo )
{
if( rStateInfo.sState.nItemType == m_nItemType )
{
++m_nNumItems;
}
return true;
}
uint8& m_nNumItems;
uint8 m_nItemType
};
void IterateStateInfo( IIterationFunctor& functor )
{
for (TStateInfoIterator itStateInfo = m_lstStateInfos.Begin();
itStateInfo != m_lstStateInfos.End();
itStateInfo++)
{
SStateInfo* pStateInfo = *itStateInfo;
// If a functor returns false don't continue processing
if(!functor(*pStateInfo))
{
return;
}
}
}
void SomeFunction()
{
uint8 nNumItems;
IterateStateInfo(SNumItemsFunctor(nNumItems, 3));
}
正如我上面提到的,它适用于VS2008,但不能用G ++编译,它给出了错误: 错误:没有用于调用'IterateStateInfo(SNumItemsFunctor)'的匹配函数 注意:候选人是:void IterateStateInfo(IIterationFunctor&)
显然,如果我定义一个局部变量,它的工作原理如下:
void SomeFunction()
{
uint8 nNumItems;
SNumItemsFunctor functor(nNumItems, 3));
IterateStateInfo(functor);
}
但是有没有办法在没有局部变量的G ++(我假设C ++扩展)中做到这一点?
答案 0 :(得分:5)
问题是不允许void IterateStateInfo( IIterationFunctor& functor )
接受匿名临时绑定到非const引用参数。 g ++禁止它并且MSVC错误是正确的。你需要将该参数作为const引用,它应该可以工作。