Search code examples
c++functionfunctorstd-function

What is the most efficient way to pass a non generic function?


I am learning functional programming in C++. My intention is to pass a non generic function as argument. I know about the template method, however I would like to restrict the function signature as part of the API design. I worked out 4 different methods example on cpp.sh:

// Example program
#include <iostream>
#include <string>
#include <functional>

typedef int(functor_type)(int);


int by_forwarding(functor_type &&x)  {
    return x(1);
}

int functor_by_value(functor_type x) {
    return x(1);
}

int std_func_by_value(std::function<functor_type> x) {
    return x(1);
}

int std_func_by_forwarding(std::function<functor_type> &&x) {
    return x(1);
}

int main()
{
    std::cout << functor_by_value([](int a){return a;}); // works
    std::cout << std_func_by_value([](int a){return a;}); // works
    std::cout << std_func_by_forwarding(std::move([](int a){return a;})); // works

    //std::cout << by_forwarding([](int a){return a;}); // how to move lambda with forwarding ?
}

Is any of the above attempts correct? If not, how do i achieve my goal?


Solution

  • (based on clarification from comments)

    Signature can be restricted by using std::is_invocable:

    template<typename x_Action> auto
    functor_by_value(x_Action && action)
    {
        static_assert(std::is_invocable_r_v<int, x_Action, int>);
        return action(1);
    }
    

    online compiler