简体   繁体   中英

Returning a function object from a function C++

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'

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.

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 );

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);

I resolved it with a templates function:

template<typename F>
F foo(F func)

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