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

时间:2016-04-28 16:30:33

标签: 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;
};

1 个答案:

答案 0 :(得分:11)

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

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

Demo