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

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

问题描述

在斯科特·迈耶(Scott Meyer)的书中

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限定的时:

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

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

演示

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

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