1

I have this code on Win32:

Actor* Scene::GetActor(const char* name)
{
    StringID actorID(name);

    auto actor = find_if(m_actors.begin(), m_actors.end(), [&](Actor* actor){return actor->GetName() == actorID;});
    return  actor != m_actors.end() ? *actor : NULL;
}

Because this couldn't be compiled on iPhone with GCC/LLVM Clang I want to removed C++11 features from it. Is there any other easy way of using STL algorithms without using C++11 features? I don't want to declare simple function like this compare function everywhere in the code.

Mircea Ispas
  • 20,260
  • 32
  • 123
  • 211

3 Answers3

7

You can try to implement a generic predicate for this, something along these lines (demo here):

template<class C, class T, T (C::*func)() const>
class AttributeEquals {
public:
    AttributeEquals(const T& value) : value(value) {}

    bool operator()(const C& instance) {
        return (instance.*func)() == value;
    }
private:
    const T& value;
};

This would require some more tweaking, since in your case you are working with pointers, but you get the general idea.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • In a similar vein, http://stackoverflow.com/questions/5174115/sorting-a-vector-of-objects-by-a-property-of-the-object/5174694#5174694 – ildjarn Oct 07 '11 at 15:57
4

Have you tried using Blocks?

auto actor = find_if(m_actors.begin(), m_actors.end(),
                     ^(Actor* actor){return actor->GetName() == actorID;});
Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
2

Rather than using an anonymous function, you'll have to define and construct a functor. You'll also have to drop the auto keyword.

Actor* Scene::GetActor(const char* name)
{
    StringID actorID(name);
    MyFunctor funct(actorID); // move code from anon function to operator() of MyFunctor
    // Replace InputIterator with something appropriate - might use a shortening typedef
    InputIterator actor = find_if(m_actors.begin(), m_actors.end(), funct);
    return  actor != m_actors.end() ? *actor : NULL;
}

If StringID is your own class, you can make it a functor by defining operator().

01d55
  • 1,872
  • 13
  • 22