0

In the following example, I've implemented two ways of traversing a data structure. One uses a result vector which implies copies while the other uses a callback.

Which of the two approaches is usually better to use in typical C++ applications? Said differently, does one solution have flaws/drawbacks?

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

using namespace std;

template<typename T>
class Foo {
    vector<T> v;

    vector<T> query(T query) {
        vector<T> results;
        for (auto &k : v)
            if (match(query, k))
                results.push_back(k);
    }

    void query(T query, const std::function<void(T&)>&cb) {
        for (auto &k : v)
            if (match(query, k))
                cb(k);
    }
};

template<typename T>
void display(Foo<T> &foo, T &query) {
    for(auto el : foo.query(query))
       cout << el << endl;

    foo.query(query, [](T &el) {
        cout << el << endl;
    });
}

1 Answer 1

3

In this case I would use the callback approach, but I would remove the std::function and replace it with a template type. std::function uses type erasure and that requires dynamic allocation and a little bit of overhead. A function template like

template<typename Callback>
void query(T query, const Callback& cb) {
    for (auto &k : v)
        if (match(query, k))
            cb(k);
}

will remove that overhead and still let you pass any function object you want to the function.

2
  • I thought about the template approach, but it is less clear for the intelli-sense. The developer could try to do query(query, 42) without any warning until build time. So it is a matter of readability vs performance...
    – nowox
    Nov 6, 2020 at 16:16
  • 1
    @nowox In that case you can add SFINAE using std::is_invocable to make sure Callback is a type that is invocable for the parameters you want. Nov 6, 2020 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.