在C ++ 11

时间:2018-04-12 08:12:07

标签: c++ c++11 lambda

我有以下类,其中包含一个lambda成员变量:

template <typename Callable>
class task {
  private:
    Callable lambda;

  public:
    task(Callable l) : lambda(l) {}

    void execute() {
        lambda();
    }
};

现在我想创建一个函数,它接受任何类的对象和该类的成员函数指针,然后创建lambda,从该lambda创建一个任务,最后返回任务。但我无法弄清楚函数的返回类型:

template <typename C, typename F, typename ...Args>
/* return type ?*/ create_task(C& obj, F func, Args... args) {
    auto l = [&obj, func, args...] {
        (obj.*func)(args...);
    };

    task<decltype(l)> t {l};

    return t;
}

如何在C++11中完成此操作?我也开放其他建议,但他们不得不做动态内存分配。

1 个答案:

答案 0 :(得分:3)

由于类型推导在C ++ 11中的工作方式有限,你必须推出自己的可调用而不是使用lambda

  router.post('/', function (req, res, next) {
  let city = req.body.location;
  let from = req.body.from;
  let to = req.body.to;


  let url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D%22" + encodeURI(city) + "%22&format=json";
  /*Using Twit library*/
  request(url, function (err, response, body) {
    var woeidData = JSON.parse(body);
    var woeid = woeidData.query.results.place[0].woeid;
    var tweets = [];
    var T = new Twit({
      consumer_key: "**",
      consumer_secret: "**",
      access_token: "**",
      access_token_secret: "**",
      timeout_ms: 60 * 1000,
    });
    T.get('trends/place', {
      id: woeid ,
      //q:'since 2011-07-11'
    }, function (err, data, response) {
      var converted = JSON.stringify(data);
      objects = JSON.parse(converted);

      tweets = objects[0].trends;
      //console.log(tweets[0]);
      for (let i = 0; i < tweets.length; i++) {
        console.log("tweet is about" + tweets[i]);
      }
      //{tweetsData : tweets,data:true}
      res.render('index');
    });
  });
});

template<typename C, typename F, typename... Args> struct task { C* c; F C::* f; std::tuple<typename std::decay<Args>::type...> args; task(C* c, F C::* f, Args&&... args) : c{c}, f{f}, args{std::forward<Args>(args)...} {} void execute() { auto l = [&](Args&... args) { (c->*f)(args...); }; std::apply(l, args); } }; template<typename C, typename F, typename... Args> auto create_task(C& c, F C::* f, Args&&... args) -> task<C, F, Args...> { return {&c, f, std::forward<Args>(args)...}; } 可以在{+ 3}}等C ++ 11中实现。{/ p>