Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

c++ - Purpose of perfect forwarding for Callable argument in invocation expression?

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;
};

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;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
"; }
};

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...