简体   繁体   中英

Are std::functions inlined by the C++11 compiler?

I'm working on a small mathematical optimization framework in C++11, and I wonder what's the best way for the user to provide domain-specific logic. I could force her to define classes with hook methods that can be called by the framework, but I'd like to keep it lean and take advantage of the new C++11 facilities whenever I can. So I'm thinking about accepting std::function objects, possibly instantiated from lambda expressions, as parameters, and call them when needed. The only think I'm wondering about is whether the compiler (in my case gcc, but I'd like to know about Xcode and Visual C++ as well) will be able to take the std::function objects and inline the function definitions, so that they are optimized together with the rest of the code.

PS: from the comments, it looks like the first revision of my question was obscure to most of the users, probably my fault for using an incorrect language. So I have reworded it, I hope someone can understand the concept I'm trying to convey here (and possibly suggest a solution).

PPS: someone suggested to use templates, that is an idea I have thought about, but I'd like to know if there's an alternative. I don't have anything against templates, but I plan to make a template-based version as soon as this one is working because I find it easier to reason in terms of dynamic objects.

std::function is a callable object which can store any callable object. It is as flexible as possible, by design. That design however comes with drawbacks. Because function s could contain pretty much anything (callable), they must be able to work with anything .

Internally, function has no idea at compile-time what it might be storing. Since this determination is made a runtime, it is pretty much impossible for most normal compilers to inline through that. Inlining through a function pointer is possible, but only if it's locally known what the value of that pointer is. function is a lot more complex than a mere function pointer.

It is theoretically possible to inline such a thing, but only as part of some kind of profile-guided optimization system, where repeated execution of the code is able to determine that certain function objects will always be used with certain contents and thus to inline them. But even that is

If you want inlining for an arbitrary callable object, you should use a template function, not std::function . function is for when you can't use templates (perhaps because you need to store multiple functions in a container, or because you don't want to break encapsulation, or whatever), yet still need to store arbitrary callables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM