Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a function that receives a function, calls it and returns it on C++?

Tags:

c++

function

I'm trying to create a function that receives a function, calls it and returns it back. I've tried several things already, including a lot of template combinations, an none seems to work. What is the correct way to do this?

like image 344
MaiaVictor Avatar asked Dec 29 '25 17:12

MaiaVictor


1 Answers

template <typename Functor>
Functor your_function(Functor toCall)
{
    toCall();
    return toCall;
}

If you want to return what the functor returns, then you'd use something like:

// Requires C++11
#include <type_traits>

template <typename Functor>
typename std::result_of<Functor()>::type your_function(Functor toCall)
{
    return toCall();
}

Also note that this will get easier in C++14 with decltype(auto):

//Requires C++14    
template <typename Functor>
decltype(auto) your_function(Functor toCall)
{
    return toCall();
}
like image 61
Billy ONeal Avatar answered Jan 01 '26 08:01

Billy ONeal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!