c – 通过通用引用传递的函数的std :: forward吗?

前端之家收集整理的这篇文章主要介绍了c – 通过通用引用传递的函数的std :: forward吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑以下两点:
  1. template <class Function>
  2. void apply(Function&& function)
  3. {
  4. std::forward<Function>(function)();
  5. }

  1. template <class Function>
  2. void apply(Function&& function)
  3. {
  4. function();
  5. }

在什么情况下有差异,它有什么具体的区别?

解决方法

如果Function的operator()具有ref限定符,则会有所不同.使用std :: forward,参数的值类别将被传播,如果没有它,则值类别将丢失,并且函数将始终作为l值调用. Live Example.
  1. #include <iostream>
  2.  
  3. struct Fun {
  4. void operator()() & {
  5. std::cout << "L-Value\n";
  6. }
  7. void operator()() && {
  8. std::cout << "R-Value\n";
  9. }
  10. };
  11.  
  12. template <class Function>
  13. void apply(Function&& function) {
  14. function();
  15. }
  16.  
  17. template <class Function>
  18. void apply_forward(Function&& function) {
  19. std::forward<Function>(function)();
  20. }
  21.  
  22. int main () {
  23. apply(Fun{}); // Prints "L-Value\n"
  24. apply_forward(Fun{}); // Prints "R-Value\n"
  25. }

猜你在找的C&C++相关文章