Can't include <functional> in JUCE files


#1

I'm fooling around with C++11 and wanted to add a method to OwnedArray that will return an array with all of the elements that satisfy some condition.

Here's the method:


    Array<ObjectClass*> getAllThatSatisfy(std::function<bool(ObjectClass*)> func)
    {
        const ScopedLockType lock(getLock());
        ObjectClass** const e = data.elements.getData();

        Array<ObjectClass*> res;

        for (int i = 0; i < numUsed; ++i)
        {
            if (func(e[i]))
            {
                res.add(e[i]);
            }
        }

        return res;
    }

When I try to include <functional> in OwnedArray.h, I get an infinite number of syntax errors, mostly in the files tuple and xfuctional (I'm using Windows 8.1 update 1 and Visual Studio 2013 update 2).

Including functional in my own files generate no errors. I'm new to both C++11 and JUCE, so any help would be appreciated.


#2

Have a look through a few juce header files - do you see them including any other 3rd-party includes? Nope. Those classes are all declared inside the juce namespace, and there's no guarantee what'd happen if you try pulling in standard library code inside some other namespace!

But more importantly: you shouldn't be trying to do that! You don't need to mess with the juce source files to add functionality like that - the consensus nowadays is that it's better to extend functionality where possible by adding free functions, not member functions. In your own code you could write a function e.g.

template <typename ObjectClass>
static Array<ObjectClass*> getAllThatSatisfy (const OwnedArray<ObjectClass>&, std::function<bool(ObjectClass*)> func)

..which will do exactly the same job without needing to couple this functionality to the original class. You could also abstract it further so that it'll take any kind of array, not just an OwnedArray. And TBH you can probably don't even need to write this anyway, as you can use standard library algorithms like std::find on juce containers, as they provide normal iterators.


#3

Thanks for the response.

I've found a neat way of doing it using the standard library alogorithms.

I see what you mean about free functions, but would it be necessary to specify the template name every time I use it? 


#4

I see what you mean about free functions, but would it be necessary to specify the template name every time I use it? 

No - the compiler would figure that out.