example1_perfect_fowarding.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <utility>  // for std::forward

void process(int& x) {
    std::cout << "Lvalue reference: " << x << std::endl;
}

void process(int&& x) {
    std::cout << "Rvalue reference: " << x << std::endl;
}

template<typename T>
void forwarder(T&& arg) {
    process(std::forward<T>(arg));  // Forward the argument with its original value category
}

int main() {
    int a = 10;

    forwarder(a);          // Calls process(int&), lvalue reference
    forwarder(20);         // Calls process(int&&), rvalue reference
    forwarder(std::move(a));  // Calls process(int&&), rvalue reference

    return 0;
}
Back to std_forward