【发布时间】:2018-03-27 07:13:59
【问题描述】:
在Swift中,当我们需要将闭包作为函数的参数传递时,如果闭包是最后一个要传递的参数,我们可以在调用函数的最后一个括号)之后指定闭包体,即称为a尾随闭包。
Swift 示例:
func someFunctionThatTakesAClosure(closure: () -> Void) {
// function body goes here
}
// Here's how you call this function without using a trailing closure:
someFunctionThatTakesAClosure(closure: {
// closure's body goes here
})
// Here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}
有时在 C++ 中,当我使用 std::sort 并传递一个闭包时,如果我使用等效于 Swift 尾随闭包的代码,则代码将更具可读性。 我对 C++ 11 之后的 C++ 标准的经验很少,你知道 C++ 中是否有类似的东西?
【问题讨论】:
-
您能否在
C++中发布您想做的真实(工作)示例? -
不,而且 C++ 有不同的 lambda 语法,所以会引入不一致。