Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Template and Lambda

Tags:

c++

Is it common to use something like the following in C++?

template <typename T> function<void(vector<T> &)> filter1 = [ ] (vector<T> &vec){
    int count = 0;
    for (T t : vec){
        if ( t.cost < 500 )
            vec.erase(vec.begin()+count);
        count++;
    }
};

template <typename T> void discount(float p, vector<T> &vec){
    filter1<T>(vec);
    int count = 0;
    for (T t : vec) {
        t.cost = t.cost - t.cost * p;
        vec.erase(vec.begin() + count);
        vec.emplace(vec.begin() + count, t);
        count++;
    }

btw I'm calling it tembda, cause its a mixture of Template and Lambda.

like image 682
SecretOne Avatar asked Sep 14 '26 17:09

SecretOne


1 Answers

Is it common to use something like the following in C++?

No.

Firstly, std::function is a heavyweight abstraction which unnecessarily degrades the performance of your code in this case. Secondly, there's no advantage in using a lambda expression here over a simple template function - you are just going to confuse whoever reads your code.

like image 193
Vittorio Romeo Avatar answered Sep 16 '26 05:09

Vittorio Romeo



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!