SecretOne
SecretOne

Reputation: 23

C++: Template and Lambda

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.

Upvotes: 2

Views: 126

Answers (2)

Taylor Nichols
Taylor Nichols

Reputation: 618

Template lambdas will be a part of C++20, but your intent was common enough to include in C++14.

C++14 supports this via auto instead of <typename T>:

auto filter_out_low_prices = [] (auto& vec) {
    auto predicate = [](const auto& t){ return t.cost < 500.00; };
    vec.erase(std::remove_if(std::begin(vec), std::end(vec), predicate),
            std::end(vec));
};

template <class V>
void discount(const float p, V& vec){
    filter_out_low_prices(vec);
    for (auto& t : vec)
        t.cost = t.cost - t.cost * p;
}

This avoids the use of std::function to be lightweight, as Vittorio Romeo suggested. It also uses remove_if to avoid undefined behavior and is not limited to std::vector, as doctorlove suggested.

Upvotes: 3

Vittorio Romeo
Vittorio Romeo

Reputation: 93264

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.

Upvotes: 6

Related Questions