inline function parameters in c++

This is a note on how to inline functions that are passed as parameters (argumetns) of a function, using templates.

There are four ways to pass in function as parameters to a function in C++

  1. functor (struct with overloaded operators and methods)
  2. lambda functions
  3. function type (treat it as a value, with a function type)
  4. function pointer (treat function as a pointer)

The object passed to it may be:

  • a functor:
    struct Functor {
        void operator()() const {
            std::cout << "functor!" << std::endl;
        }
    };
  • a function:
    void function( ) {
        std::cout << "function!" << std::endl;
    }
  • a (C++0x) lambda function:
    [](){ std::cout << "lambda!" << std::endl; }

Apparently, the first three options can be inlined with a templated function

template< typename Function > void functionProxy( Function function ) {
    function();
}

Templated function declarations work by creating multiple copies of the functions that have replaced typename with actual concrete types. This way, the compiler knows exactly which function is being called during compile time, enabling inlining of functions.

Apparently, the first three approaches can be inlined per the post below

https://stackoverflow.com/questions/4860762/c-can-compilers-inline-a-function-pointer

Function pointer (approach 4) is the only one that can’t be inlined as the exact function can’t be inferred at compile time.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s