c++ - 调用表达式中 Callable 参数的完美转发目的?

标签 c++ lambda c++14 auto perfect-forwarding

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

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 的完美转发何时会相关。换句话说,上面的优点是什么:

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

最佳答案

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

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

Demo

关于c++ - 调用表达式中 Callable 参数的完美转发目的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36920485/

相关文章:

lambda - 关于 Java 8 中的功能接口(interface), "function shape"是什么?

c++ - 没有 Boost 的现代 C++ 中的 bimap 实现

c++ - 在模板函数和自动类型推导之间选择

c++ - C++14 是否定义了 'auto' 类型的函数参数?

c++ - iOS中Opencv人脸检测Cascade编译器报错

C++/VS2005 : Defining the same class name in two different . cpp文件

c++ - 使用可变函数/宏简化工作

c++ - 使用模板和基类实现灵活的数组成员

lambda - 范围函数 apply/with/run/also/let : Where do their names come from?

android - Kotlin-内联参数回调的非法使用