Home > other >  Passing C lambda as argument to non templated function
Passing C lambda as argument to non templated function

Time:08-07

As I googled std::function works slower than simple lambda function.

Consider the following use case will there be std::function penalty when using stl sorting algorithms (v vector may be big enough and occupy about N*GB of data):

#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>

using namespace std;

void sorter(std::vector<int>& v, std::function<bool(int a, int b)> f){
    std::sort(v.begin(), v.end(), f);
}

int main()
{
    std::vector<int> v = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
    for (auto val : v)
        cout << val << " ";
    cout << endl;

    int c = 4;
    auto f = [&c](int a, int b){ return a b < c; };
    
    sorter(v, f);

    for (auto val : v)
        cout << val << " ";
    cout << endl;

    return 0;
}

As you can see I create the lambda function f and pass it to a sorter function. My task is to keep sorter function non-templated that is why I tried to pass lamda function as std::function. Or are there better ways of doing that?

CodePudding user response:

Lambdas that do not capture anything can be converted to a function pointer with the operator:

void sorter(std::vector<int>& v, bool (*cmp)(int,int));

int main() {
  auto const cmp =  [](int a, int b) { return a < b; };
  vector<int> v{3, 2, 1};
  sorter(v, cmp);
}

But if it does capture something, you should either make it a template, or use std::function. No way around that.

  • Related