MartinYakuza
MartinYakuza

Reputation: 135

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?

Upvotes: 0

Views: 302

Answers (3)

WBuck
WBuck

Reputation: 5503

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

Upvotes: 0

Alberto
Alberto

Reputation: 12909

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.

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234665

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

Upvotes: 2

Related Questions