考虑以下两点:
- template <class Function>
- void apply(Function&& function)
- {
- std::forward<Function>(function)();
- }
和
- template <class Function>
- void apply(Function&& function)
- {
- function();
- }
在什么情况下有差异,它有什么具体的区别?
解决方法
如果Function的operator()具有ref限定符,则会有所不同.使用std :: forward,参数的值类别将被传播,如果没有它,则值类别将丢失,并且函数将始终作为l值调用.
Live Example.
- #include <iostream>
- struct Fun {
- void operator()() & {
- std::cout << "L-Value\n";
- }
- void operator()() && {
- std::cout << "R-Value\n";
- }
- };
- template <class Function>
- void apply(Function&& function) {
- function();
- }
- template <class Function>
- void apply_forward(Function&& function) {
- std::forward<Function>(function)();
- }
- int main () {
- apply(Fun{}); // Prints "L-Value\n"
- apply_forward(Fun{}); // Prints "R-Value\n"
- }