Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何推导函子的类型';返回值是多少?_C++_Templates_C++11 - Fatal编程技术网

C++ 如何推导函子的类型';返回值是多少?

C++ 如何推导函子的类型';返回值是多少?,c++,templates,c++11,C++,Templates,C++11,我想写一个模板函数,它接受2个值和一个函子或lambda。 该函数使用这些值调用函子并返回结果 template <typename T, typename Fn> _ReturnTypeOfPred_ Apply(T x, T y, Fn fn) { return fn(x, y); } 更新 第一个例子过于简单化了。 这个能用吗 template <typename TContainer, typename Fn> auto Apply(const

我想写一个模板函数,它接受2个值和一个函子或lambda。 该函数使用这些值调用函子并返回结果

template <typename T, typename Fn> 
_ReturnTypeOfPred_ Apply(T x, T y, Fn fn)
  {
  return fn(x, y);
  }
更新

第一个例子过于简单化了。 这个能用吗

template <typename TContainer, typename Fn> 
auto Apply(const TContainer& x, const TContainer& y, Fn fn) -> decltype(fn(x.front(), y.front()))
  {
  return fn(x.front(), y.front());
  }
模板
自动应用(常量容器&x,常量容器&y,Fn-Fn)->decltype(Fn(x.front(),y.front())
{
返回fn(x.前(),y.前());
}

如果我在返回类型的
decltype
中重复
return
表达式,它是否总是有效?还有更优雅的方式吗?

你就快到了;只需使用
decltype

template <typename T, typename Fn> 
auto Apply(T x, T y, Fn fn) -> decltype(fn(x, y))
{
  return fn(x, y);
}

关于后续问题:功能

auto fn(<args>) -> <return-type> { return <expression>; }
在这里,
decltype
将产生
std::string&
,并且您的函数将返回对本地的左值引用!这必须更改为:

auto f(char c) -> std::remove_reference<decltype(std::string() += c)>::type {
    return std::string() += c;
}
auto f(char c)->std::remove\u reference::type{
返回std::string()+=c;
}

在其他情况下,
可能会产生一个由于不可复制、包含lambda等原因而不可返回的值。

下划线大写名称保留用于实现。你不能在自己的代码中使用它们。@KerrekSB:这是一个占位符,不是真正的代码好的函子(比如STL中的函子)总是定义它们的
return\u类型
,所以你可以只使用
Fn::return\u类型
。但我知道你想要一个同样适用于不太好的函子的答案。@Gorpik:如果函子是lambda呢?@Andrey:啊,那你真是太棒了。ecatmur的答案在这里是正确的。谢谢,您能看一下更新的问题吗?您链接的问题没有突出显示
std::result\u of
decltype
之间的差异。就OP而言,的std::result_不合适。
auto fn(<args>) -> <return-type> { return <expression>; }
auto f(char c) -> decltype(std::string() += c) { return std::string() += c; }
auto f(char c) -> std::remove_reference<decltype(std::string() += c)>::type {
    return std::string() += c;
}