Home > Back-end >  Returning a function object from a function C
Returning a function object from a function C

Time:07-22

let the following function:

returntype Foo(void(*bar)(const C&));

what should be inserted instead of 'returntype' in order for Foo returning the passed function\functor aka 'bar'

CodePudding user response:

Method 1

One option with C 11 is to use placeholder type auto in the return type with decltype using the trailing return type syntax as shown below:

auto Foo(void(*bar)(const C&)) -> decltype(bar); //this is more readable than method 2 below

Method 2

void (*Foo(void(*bar)(const C&)))(const C&); //less readable than method 1 above

As we can see, method 1 is more readable than method 2.

CodePudding user response:

A direct approach is the following

void ( *Foo(void(*bar)(const C&)) ( const C & );

Or you could use a using or typedef alias like

using Fp = void ( * )( const C & );

or 

typedef void ( *Fp )( const C & );

and after that

Fp Foo( Fp bar );

CodePudding user response:

Suppose you have a function void bar(const C&), and consider Foo(bar).

In order to call the returned function pointer, you need to dereference it first, (*Foo(bar)), and then pass it a const C& (let's call it "the_c"):

(*Foo(bar))(the_c)

Since fn returns void, you can now fill in the types:

    void (*Foo(void(*bar)(const C&)))(const C&)
      ^        ^                  ^      ^
      |        |<-  parameter   ->|      | parameter for the returned function       
      |
 Ultimate result

Or, you could decide to not give up on your sanity yet, and name the type:


using function = void(*)(const C&);
function Foo(function bar);
  • Related