Could/should var support std::function?


At the moment I am thinking it would be great if Juce's var would support storing std::functions, since it would allow using C++11 lambdas with captures. But are there reasons that shouldn't or couldn't be done? I see var supports "NativeFunction" as a type, but wouldn't std::function be more flexible and easier to use?


Well, the main reason is that Juce needs to be compatible with C++98, at least at the moment, so if we add this we could only do so if we surround it with #if JUCE_COMPILER_SUPPORTS_LAMBDAS. Also, if you use a std::function with lambdas or functor objects, there is significant overhead when copying around the resulting std::function objects, and if you capture stuff in the lambda, you have to worry about lifetime etc., which makes everything more complicated - whereas NativeFunction is just a typedef'd raw function pointer.

So, yes, std::function is definitely more flexible than NativeFunction, but I'm not sure what the use case would be using it together with a var. Do you have a specific use case in mind where a var supporting std::function would help you write better code? Or is this more like a general idea?


More a general idea at the moment, I haven't even needed the NativeFunction type with a Juce var yet.

I am currently looking into a tricky problem though, where I would need to be able to store a number, a string or a function in a class and to avoid having to write a lot of constructor overloads and have a different class member variable for each of those, a variant that could hold the function would become handy. I have not however even used Juce yet for this code. Using Boost's variant might be an option but I don't often like the idea of having to use Boost, since not all of the stuff is header-only and even if it is, then the compile times will just blow up...


You could always wrap a std::function in a ReferenceCountedObject?