繁体   English   中英

如何确定C ++ lambda的结果类型(Closure Type)

[英]How to determine the result type of a C++ lambda (Closure Type)

我正在尝试编写一个与std::function或lambda一起使用的模板函数。 让我们假设一个这样的apply模板:

template<typename F>
typename F::result_type apply(const F &f) {
    return f();
}

如果我用std::function<int()>调用它,这很好,但是如果用[]() -> int { return 1; } []() -> int { return 1; }因为拉姆达的闭合类型不具有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

对于C ++ 14,您应该使用decltype(auto)

template<typename F>
decltype(auto) apply(const F &f) {
    return f();
}

对于pre-C ++ 14,您可以使用Boost.FunctionTypes result_type

template<typename F>
typename boost::function_types::result_type<F>::type apply(const F &f) {
    return f();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM