Callback Dispatch: std::function vs Template Parameter

Question 15 / 17 Correct so far: 0 (0 answered)

Snippet A

Std Function Callback

int accumulate(const std::vector<int>& v,
               const std::function<int(int, int)>& fn) {
    int acc = 0;
    for (int x : v) acc = fn(acc, x);
    return acc;
}

int result = accumulate(values, add);
Snippet B

Template Callback

template <typename Fn>
int accumulate(const std::vector<int>& v, Fn fn) {
    int acc = 0;
    for (int x : v) acc = fn(acc, x);
    return acc;
}

int result = accumulate(values, add);
Shared test data (shared-setup)
constexpr int kN = 1024;
static std::vector<int> values(kN);

struct ValuesInit {
    ValuesInit() { std::iota(values.begin(), values.end(), 1); }
} _values_init;

Which snippet is faster?

Select the correct answer(s)