C++笔记之std::forward

C++笔记之std::forward

文章目录

std::forward的作用是在C++中帮助实现完美转发(perfect forwarding),它将传递给它的参数以原始类型和引用的方式传递给下一个函数,保持参数的值类别(lvalue或rvalue)不变。这有助于确保传递给下一个函数的参数类型与调用者传递的参数类型一致,从而实现更灵活的函数参数传递。

例一

代码

cpp 复制代码
#include <utility>

template <typename T>
void process(T&& arg) {
    // 使用 std::forward 将参数 arg 完美转发给另一个函数
    // 这里的 std::forward 会保留 arg 的原始类型和引用性质
    another_function(std::forward<T>(arg));
}

void another_function(int& x) {
    // 处理左值引用
}

void another_function(int&& x) {
    // 处理右值引用
}

int main() {
    int value = 42;
    process(value);      // 调用左值版本的 another_function
    process(123);        // 调用右值版本的 another_function
}

例二

代码

cpp 复制代码
#include <iostream>
#include <utility>

// 使用完美转发的函数模板
template <typename T>
void forwarder(T&& arg) {
    // 调用另一个函数,并将参数完美转发
    some_function(std::forward<T>(arg));
}

// 示例函数,可以接受各种类型的参数
void some_function(int& i) {
    std::cout << "Lvalue reference: " << i << std::endl;
}

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

int main() {
    int x = 42;

    // 调用 forwarder 时,完美转发参数 x
    forwarder(x); // 输出 "Lvalue reference: 42"

    // 可以通过将临时对象传递给 forwarder 来完美转发右值
    forwarder(123); // 输出 "Rvalue reference: 123"

    return 0;
}
相关推荐
齐生13 小时前
iOS 知识点 - 渲染机制、动画、卡顿小集合
笔记
用户9623779544811 小时前
VulnHub DC-1 靶机渗透测试笔记
笔记·测试
樱木Plus1 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
齐生11 天前
iOS 知识点 - IAP 是怎样的?
笔记
tingshuo29172 天前
D006 【模板】并查集
笔记
tingshuo29173 天前
S001 【模板】从前缀函数到KMP应用 字符串匹配 字符串周期
笔记
blasit3 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_4 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星4 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛6 天前
delete又未完全delete
c++