在调用表达式中完美转发 Callable 参数的目的? [英] Purpose of perfect forwarding for Callable argument in invocation expression?

查看:29
本文介绍了在调用表达式中完美转发 Callable 参数的目的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scott Meyer 的书中 Effective Modern C++ on page 167(印刷版),他给出了以下示例:

In Scott Meyer's book Effective Modern C++ on page 167 (of the print version), he gives the following example:

auto timeFuncInvocation = [](auto&& func, auto&&... params) {
  // start timer;
  std::forward<decltype(func)>(func)(
    std::forward<decltype(params)>(params)...
  );
  // stop timer and record elapsed time;
};

我完全理解 params 的完美转发,但我不清楚 func 的完美转发何时相关.换句话说,上面的比下面的有什么优势:

I completely understand the perfect forwarding of params, but it is unclear to me when perfect forwarding of func would ever be relevant. In other words, what are the advantages of the above over the following:

auto timeFuncInvocation = [](auto&& func, auto&&... params) {
  // start timer;
  func(
    std::forward<decltype(params)>(params)...
  );
  // stop timer and record elapsed time;
};

推荐答案

出于与参数相同的目的:所以当 Func::operator() 是 ref-qualified 时:

For the same purpose as for arguments: so when Func::operator() is a ref-qualified:

struct Functor
{
    void operator ()() const &  { std::cout << "lvalue functor
"; }
    void operator ()() const && { std::cout << "rvalue functor
"; }
};

演示

这篇关于在调用表达式中完美转发 Callable 参数的目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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