Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • 7
    That is going to cause a memory allocation though in the constructor of std::function. Commented Jan 18, 2011 at 21:11
  • 2
    @Maxim Yegorushkin std::function has move semantics plus it can use custom allocators and the C++0x working draft has these notes: "[Note: implementations are encouraged to avoid the use of dynamically allocated memory for small callable objects, for example, where f’s target is an object holding only a pointer or reference to an object and a member function pointer. —end note ]" so basically you can not make many assumptions as to what allocation strategy a particular implementation is using but you should be able to use your own (pooled) allocators anyway. Commented Jan 18, 2011 at 23:58
  • @Sean: you could as well wrap it into boost::any. The question was how to specify the return type. This answer sidesteps the question. Commented Jan 19, 2011 at 9:36
  • 1
    @Maxim: My answer was to the question "Is the only solution handcrafting a function object and returning it?" Commented Jan 19, 2011 at 18:11
  • 4
    Just keep in mind that std::function employs type erasure, which can mean the cost of making a virtual function call when calling the std::function. Something to be aware of if the returned function is going to be used in a tight inner loop or other context where the slight inefficiency matter. Commented Dec 17, 2016 at 6:05