C ++ 11 result_of推导我的函数类型失败 [英] C++11 result_of deducing my function type failed

查看:158
本文介绍了C ++ 11 result_of推导我的函数类型失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试下面的程序:

#include<type_traits>
using namespace std;
template <class F, class R = typename result_of<F()>::type>
R call(F& f) { return f(); }
int answer() { return 42; }

int main()
{
    call(answer); 
    return 0;
}

call(answer)无法编译

"call(answer)" fails to compile

VC说'R调用(F&)'不能推导出'R'的模板参数

VC says 'R call(F&)' could not deduce template argument for 'R'

GCC说|注意:模板参数扣除/ replace failed:| error:函数返回一个函数

GCC says |note: template argument deduction/substitution failed:|error: function returning a function

我不知道一个函数名称是否可以用于模板。我在哪里错了,如何使我的电话(答案)工作?

I'm not sure if a "function name" could be used for templates. Where did I get wrong, how to make my call(answer) work?

推荐答案

您可以在这些情况下使用转寄参考:

You can use forwarding references in these cases:

#include<type_traits>
#include<utility>
#include<cassert>

using namespace std;

template <class F, class R = typename result_of<F()>::type>
R call(F&& f) { return std::forward<F>(f)(); }

int answer() { return 42; }

int main()
{
    assert(call(answer) == 42);
    return 0;
}

通常可以避免麻烦。

也就是说,为什么你的代码不工作很好地解释@TC在其答案中。

更多细节,请参阅此问题的意见。

That said, why your code doesn't work is nicely explained by @T.C. in his answer.
See also the comments to this question for further details.

这篇关于C ++ 11 result_of推导我的函数类型失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆