🐭 完美转发
完美转发指的是将一个变量,从一个函数传递到另外一个函数,再传到更内层的函数等等,整个传递过程中保持变量的类型不变,是通用引用的应用场景。之所以称为完美转发是因为:
- 相对于按值传递,传的是引用而不是副本
- 相对于按指针传递,更安全
- 能保留对象的 cvref 类型属性修饰
- 完美转发能转发任意类型
代码示例 :
#include <iostream>class X {};void func(X &&x) { std::cout << "calls func(X &&x)\n"; }void func(X &x) { std::cout << "calls func(X &x)\n"; }void func(const X &x) { std::cout << "calls func(const X &x)\n"; }void func(volatile X &x) { std::cout << "calls func(volatile X &x)\n"; }auto fwd1 = [](auto &&... params) {// accept any type of arguments and forward them to funcreturn func(std::forward<decltype(params)>(params)...);};template <typename... Ts> auto fwd2(Ts &&... params) {return func(std::forward<Ts>(params)...);}int main() {// fwd can keeps the passed in value's cvr qualifierX x00{}, x01{};X x1{};const X x2{};volatile X x3{};fwd1(std::move(x00)); // calls func(X &&x)fwd1(x1); // calls func(X &x)fwd1(x2); // calls func(const X &x)fwd1(x3); // calls func(volatile X &x)fwd2(std::move(x01)); // calls func(X &&x)fwd2(x1); // calls func(X &x)fwd2(x2); // calls func(const X &x)fwd2(x3); // calls func(volatile X &x)return 0;}
🐂 完美转发的局限性
完美转发大部分时候都能很好的工作,下列类型不能很好的与完美转发一起工作:
- 括号初始化物
- 0, NULL 作为空指针
- 没有定义的 static const 整数数据成员
- 重载函数与重载模板
- 绑定位域
代码示例 :
#include <iostream>#include <vector>void func(const std::vector<int> &v) {std::cout << "v's size is: " << v.size() << std::endl;};void func(const char *cs) {if (cs == nullptr) {std::cout << "cs is a nullptr" << std::endl;}}template <typename... Ts> void fwd(Ts &&... param) {// accept any type of arguments and forward them to funcfunc(std::forward<Ts>(param)...);}int main() {// case 1: braced initializers// auto can deduce std::initializer_list// template never deduce std::initializer_listfunc({1, 2, 3}); // v's size is: 3// fwd({1, 2, 3}); // doesn’t compileauto v = {1, 2, 3}; // workaroundfwd(v); // v's size is: 3// case 2: 0 or NULL as null pointersfunc(0), func(NULL), fwd(nullptr); // cs is a nullptr (3 times)// fwd(0); // 0 deduce to int// fwd(NULL); // NULL deduce to long// case 3: declaration only integral static const data members// declaration only integral static const data members// does not has a memory address, so can not apply reference or pointer on them// an edge case, no example// case 4: overloaded function names and template names// function template does not know which overloaded function to chosen// need to passed the right full function type// an edge case, no example// case 5: bitfields// more or less the same as case 3// can not apply reference or pointer on bitfields// an edge case, no examplereturn 0;}
:::tips 完美转发失败的情形可分为三类:
