开发者

Anonymous Functors in G++?

开发者 https://www.devze.com 2023-02-20 01:59 出处:网络
I have some code that works in VS2008 but not in G++ that works as: struct IIterationFunctor { virtual bool operator()( SStateInfo& rStateInfo ) = 0;

I have some code that works in VS2008 but not in G++ that works as:

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))
        {
            ret开发者_JAVA技巧urn;
        }
    }
}

void SomeFunction()
{
    uint8 nNumItems;
    IterateStateInfo(SNumItemsFunctor(nNumItems, 3));
}

As I mentioned above it works fine with VS2008, but doesn't compile with G++, it gives the error: error: no matching function for call to 'IterateStateInfo(SNumItemsFunctor)' note: candidates are: void IterateStateInfo(IIterationFunctor&)

Obviously if I define a local variable it works as:

void SomeFunction()
{
    uint8 nNumItems;
    SNumItemsFunctor functor(nNumItems, 3));
    IterateStateInfo(functor);
}

But is there a way to do it in G++ (And I assume the C++ extension) without the local variable?


The problem is that void IterateStateInfo( IIterationFunctor& functor ) isn't allowed to accept an anonymous temporary to bind to the non-const reference parameter. g++ is right to disallow it and MSVC is wrong. You need to make that parameter a const reference and it should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消