相关疑难解决方法(0)

如何推导出仿函数的返回值类型?

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

template <typename T, typename Fn> 
_ReturnTypeOfPred_ Apply(T x, T y, Fn fn)
  {
  return fn(x, y);
  }
Run Code Online (Sandbox Code Playgroud)

问题:如何定义返回类型Apply等于返回类型Fn?它不一定等于T,在这个仿函数的例子中

template <typename T> 
auto Sum(T x, T y) -> decltype(x+y)
  {
  return x+y;
  }
Run Code Online (Sandbox Code Playgroud)

更新

第一个例子过于简单了.这个应该有用吗?

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());
  }
Run Code Online (Sandbox Code Playgroud)

如果我在返回类型中重复return表达式,它会一直有效decltype吗?有更优雅的方式吗?

c++ templates c++11

15
推荐指数
1
解决办法
1673
查看次数

如何使函数<>参数的C++ 11函数自动接受lambdas

C++ 11同时具有lambda和std :: function <>,但不幸的是,它们有不同的类型.一个结果是,人们无法直接在高阶函数中使用lambda,例如lisp中的map.例如,在以下代码中

 #include <vector>
 #include <functional>
 using namespace std;

 template <typename A,typename B> 
 vector<B> map(std::function<B (A)> f, vector<A> arr) {
       vector<B> res;
       for (int i=0;i<arr.size();i++) res.push_back(f(arr[i]));
       return res;
}

int main () {
    vector<int> a = {1,2,3};
    map([](int x) -> int { return x;},a); //not OK

    auto id_l = [](int x) -> int { return x;};
    map(id_l,a); //not OK;

    function<int (int)> id_f = id_l;
    map(id_f,a); //OK
return 0;
}
Run Code Online (Sandbox Code Playgroud)

,直接使用lambda作为main()的第2行将无法正常工作.g++ -std=c++11 testfunc.cpp返回`... testfunc.cpp:14:37:注意:'main():: __ lambda0'不是从'std …

c++ lambda c++11

7
推荐指数
3
解决办法
1525
查看次数

标签 统计

c++ ×2

c++11 ×2

lambda ×1

templates ×1