Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 506
Afoxinabox Avatar asked Aug 16 '18 09:08

Afoxinabox


1 Answers

(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

like image 90
user7860670 Avatar answered Sep 28 '22 03:09

user7860670