gpt4 book ai didi

c++ - 我应该通过 const 引用传递一个 lambda。

转载 作者:IT老高 更新时间:2023-10-28 23:15:34 30 4
gpt4 key购买 nike

当接受 lambda 作为函数的参数时,我通常使用以下模式(按值传递的模板类):

template <class Function>
void higherOrderFunction(Function f) {
f();
}

这是否复制(关闭)参数?如果是这样,那么通过 const 引用接受 lambda 有什么问题吗?

template <class Function>
void higherOrderFunction(const Function& f) {
f();
}

一个简单的测试似乎表明这工作正常,但我想知道是否有任何我应该注意的特殊注意事项。

最佳答案

如果您通过值传递,您将复制闭包对象(假设您没有定义内联 lambda,在这种情况下它将被移动)。如果 state 的复制成本很高,这可能是不可取的,如果 state 不可复制,则编译失败。

template <class Function>
void higherOrderFunction(Function f);

std::unique_ptr<int> p;
auto l = [p = std::move(p)] {}; // C++14 lambda with init capture
higherOrderFunction(l); // doesn't compile because l is non-copyable
// due to unique_ptr member
higherOrderFunction([p = std::move(p)] {}); // this still works, the closure object is moved

如果您通过 const 引用传递,那么您不能将修改其数据成员的 mutable lambda 作为参数传递给 higherOrderFunction()因为 mutable lambda 有一个非 const operator(),你不能在 const 对象上调用它.

template <class Function>
void higherOrderFunction(Function const& f);

int i = 0;
higherOrderFunction([=]() mutable { i = 0; }); // will not compile

最好的选择是使用转发引用。然后 higherOrderFunction 可以接受调用者传递的左值或右值。

template <class Function>
void higherOrderFunction(Function&& f) {
std::forward<Function>(f)();
}

这允许编译简单的情况以及上面提到的情况。关于为什么应该使用 std::forward 的讨论,见 this answer .

Live demo

关于c++ - 我应该通过 const 引用传递一个 lambda。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31280832/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com