简体   繁体   中英

function name as parameter in c++

Let's say I have function:

double fun (int *a, int b)
{
//sth
}

and I had other function fun2 , to which I'd want to pass the above function like this:

fun2(fun);

How to define fun2 and how to use the function passed as paramter inside it?

Well the easiest way is to use template (which will deduce the type for you, without digging in function pointer and company):

template<class Funct>
double fun2(Funct my_funct){
    my_funct( /*parameters of the function, or at least something that can be casted to the required types of the function parameters*/ );
}

In poor word, you "pass" a function pointer, which can be used as a function, and so using operator() you invoke it.

This will compile with everything that has an operator()(/*parameters of my_funct*/) defined and so objects with that operator defined (for example, check functors ) or callable like functions and lambdas.

The old-fashioned way (a function pointer):

void fun2(double (*fun)(int*, int));

The C++11 and onwards way:

#include <functional>
void fun2(std::function<double(int*, int)> fun);

You can use a regular old function pointer for this. You can alias it to make it look a little nicer as a function argument.

using callback = double( * )( int* a, int b );

void fun2( callback cb )
{
    // Invoke directly.
    auto ret{ cb( nullptr, 0 ) }; 

    // Or with 'invoke'.
    ret{ std::invoke( cb, nullptr, 0 ) };
}

Calling fun2 :

fun2( [ ]( auto ptr, auto value ) { return 1.0; } );

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