example2_perfect_forwarding.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
#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));  // Perfectly forward the argument
}

int main() {
    int a = 42;
    forwarder(a);         // Passes as lvalue
    forwarder(42);        // Passes as rvalue
    forwarder(std::move(a));  // Passes as rvalue

    return 0;
}
Back to universal_reference