1

我正在尝试以下程序:

#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;
}

“呼叫(回答)”无法编译

VC 说 'R call(F&)' 不能推断出 'R' 的模板参数

GCC 说 |注意:模板参数推导/替换失败:|错误:函数返回函数

我不确定“函数名称”是否可用于模板。我在哪里弄错了,如何让我的电话(接听)工作?

4

3 回答 3

1

f作为左值调用,因此:

template <class F, class R = typename result_of<F&()>::type>
//                                               ^
R call(F& f) { return f(); }
于 2016-06-29T02:28:12.470 回答
1

在这些情况下,您可以使用转发引用:

#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 在他的回答中很好地解释了为什么你的代码不起作用。
另请参阅对此问题的评论以获取更多详细信息。

于 2016-06-29T05:49:26.110 回答
0

我想您可以避免使用第二个模板参数并使用 and 的auto组合decltype()

就像是

#include<type_traits>

using namespace std;

template <class F>
auto call(F& f) -> decltype( f() )
 { return f(); } 

int answer()
 { return 42; }

int main()
{
    call(answer); 

    return 0;
}

如果你(当你)可以使用 C++14,你可以简单地使用auto

template <class F>
auto call(F& f)
 { return f(); } 

ps:对不起我的英语不好。

于 2016-06-29T02:01:22.117 回答