C ++中的函子和lambda

时间:2018-11-09 16:53:30

标签: c++ lambda functor callable-object

std::for_each(my_data.begin(), my_data.end(),
[&result](const auto & what) {
    result += what;
});

这是我从Quora那里得到的答案。我问为什么C ++采用lambda。有人用这两段代码进行了响应,上面的代码使用lambdas,下面的代码则其他代码。它们应该是等效的,并且代码上的差异突出了lambda的优势。

template <typename T>
class add_to_impl {
    T & m_result;

    public:
    add_to_impl(T & to): m_result(to) {}
    void operator () (const T & what) { m_result += what; }
};

template <typename T>
add_to_impl<T> add_to(T & result) {
    return add_to_impl<T>(result);
}
// ... other bunch of stuff
// ... somewhere else ...
std::for_each(my_data.begin(), my_data.end(), add_to(result));

但是,我看不到add_to函数将如何生成与lambda等效的行为。

通过阅读lambda,“结果”似乎是一个全局变量。而且在我的脑海中,我认为add_to函数应按以下方式实现,以便等同于lambda:

add_to_impl<T> result; //result being some global variable 
template <typename T>
void add_to(T & what) {
    result(what); // adding to result, matching what the lambda code does.
}

1 个答案:

答案 0 :(得分:0)

No, lacking any other context is a name error, as there is nothing called result in scope. Presumably it is declared in the code not shown.

The function object dance shown is equivalent to the lambda, but as @Someprogrammerdude notes, it's better to write something like

result = std::accumulate(my_data.begin(), my_data.end(), result);

assuming we are talking about a type for which +, = and += do consistent things

相关问题