【发布时间】:2012-08-15 13:04:30
【问题描述】:
这个问题是How to deduce the type of the functor's return value?的后续问题 我正在以更抽象的方式重新制定它。
给定一个模板函数的伪代码
template <typename Arg, typename Fn>
auto ComputeSomething(Arg arg, Fn fn) -> decltype(<decl-expr>)
{
// do something
// ............
return fn(<ret-expr>)
}
其中<ret-expr>是任意表达式,其中涉及arg,我应该使用<decl-expr>来设置ComputeSomething的返回类型等于函子的返回类型。
函子可以是类、lambda 或函数指针。
目前我找到的部分解决方案。
(a) 我的链接问题的答案由 ecatmur 完成。本质上,它在<decl-expr> 中重复返回语句。问题:容易出错,如果包含局部变量则无法工作。
(b) 它只适用于函数指针
template <typename Arg, typename Ret>
Ret ComputeSomething(Arg arg, Ret(*fn)(Arg))
(c) 它假设函子的参数是Arg 类型(一般情况下可能不成立)并且要求Arg 是默认可构造的
template <typename Arg, typename Fn>
auto ComputeSomething(Arg arg, Fn fn) -> decltype(fn(Arg())
(d) 使用std::declval 应该解除默认可构造的限制,如how to deduce the return type of a function in template 中所建议的那样。谁能解释一下它是如何工作的?
template <typename Arg, typename Fn>
auto ComputeSomething(Arg arg, Fn fn) -> decltype(fn(std::declval<Arg>())
【问题讨论】:
-
很抱歉这么说,但 AFAIK 这是不可能的,因为尾随返回没有看到函数模板被定义,而正文却看到了。
标签: c++ templates lambda c++11