0

What is the correct way to pass functions (with the same input arguments/return type) as arguments to another function, without function pointers being used? I would like the function argument passed in to be inlined when it is called? Well, I just don't want the pointer indirection.

I found this:

Pass a function as an explicit template parameter

but it seems to be using function pointers.

EDIT: I'd really really really like to avoid having to create structs to store the behaviour for each function argument.

Community
  • 1
  • 1
user997112
  • 29,025
  • 43
  • 182
  • 361

1 Answers1

1

If you know the specialization at compilation time, you just need to pass type information:

void inlined_function() {}; // function you want to pass

template<typename F> void caller1() {
    inlined_function(); // not passed through pointer, call inline
}

If you have control of the inline function, implement it as a functor:

struct X {
    inline void operator()() // inline function
    {
    }
};

template<typename F> void caller2(F functor) {
    functor(); // inline call
}

Client code for the two variants:

caller1<inlined_function>();
caller2(X{});

Edit:

If you do not have control to write the functor as a structure, write an inline structure wrapper for it.

E.g., you have void inlined_function() {}; and need to write caller2. In this case, write a functor similar to X that calls inlined_function, or (better yet), a lambda:

template<typename F> void caller2(F functor) {
    functor(); // inline call
}

caller2( [](){ inlined_functor(); } );
utnapistim
  • 26,809
  • 3
  • 46
  • 82
  • Hey, I am liking your EDIT idea. So inlined_functor() could also have inlined_functor2() and these would still be normal methods in the same class? – user997112 Nov 24 '14 at 10:55
  • @user997112 - yes. Inlined functions calling each other results in an inline operation. – utnapistim Nov 24 '14 at 11:33