目录
一、泛型lambda(from c++14)
二、使用forward对参数进行转换
forward的常见用法
forward在lambda表达式
一、泛型lambda(from c++14)
auto f=[](auto x){ return func(normalize(x));};
对应的类
class SomeCompileGenneratedClass{
public:template<typename T>auto operator(T x) const { return func(normalize(x)); }// 如果normalize对待左值以及右值的方式不一样,那这个x传递就有问题
}
二、使用forward对参数进行转换
forward的常见用法
#include <iostream>
#include <utility>void func(int& x) {std::cout << "lvalue reference: " << x << std::endl;
}void func(int&& x) {std::cout << "rvalue reference: " << x << std::endl;
}template<typename T>
void wrapper(T&& arg) {func(std::forward<T>(arg));
}int main() {int x = 42;wrapper(x); // lvalue reference: 42wrapper(1); // rvalue reference: 1return 0;
}
forward在lambda表达式
auto f=[](auto &&x){ return func(normalize(std::forward<???>(x)));};
//std::forward原理
template<typename T>
T&& forward(remove_reference<T>& param)
{return static_cast<T&&>(param);
}
???写成decltype(x)
- 如果传进来的x是左值,那么auto&&x => int &x
std::forward<decltype(x)>(x) => T&&& forward(...)↓ ↓int& int &
- 如果传进来的x是右值,那么auto&&x => int &&x
std::forward<decltype(x)>(x) => T&&& forward(...)↓ ↓int&& int &&