Kay*_*Ess 3 c++ lambda functional-programming c++14
我正在尝试编写一个适用于 astd::function或 lambda的模板函数。让我们假设一个apply模板是这样的:
template<typename F>
typename F::result_type apply(const F &f) {
return f();
}
Run Code Online (Sandbox Code Playgroud)
std::function<int()>例如,如果我使用 a 调用它,这很好,但如果 a 调用它,[]() -> int { return 1; }则不行,因为 lambda 的闭包类型没有result_type成员。那么如何编写apply的返回类型以使其正常工作?
我目前正在使用 clang 3.5 和 C++14,但无论我得到什么,如果它是可移植的,那就最好了——如果有帮助,我很乐意切换到更新的编译器。
实际的例子有点复杂。我正在尝试编写类似的东西reduce,如果第一个参数是可调用的,则将参数应用于可调用对象,否则它将忽略参数并返回作为第一个参数传递的值。
reduce(0, 1, 2); // returns 0
reduce([](int a, int b) { return a+b; }, 2, 3); // return 5
Run Code Online (Sandbox Code Playgroud)
对于 C++14,您应该使用decltype(auto).
template<typename F>
decltype(auto) apply(const F &f) {
return f();
}
Run Code Online (Sandbox Code Playgroud)
对于 C++14 之前的版本,您可以使用result_typefrom Boost.FunctionTypes.
template<typename F>
typename boost::function_types::result_type<F>::type apply(const F &f) {
return f();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1214 次 |
| 最近记录: |