C++完美转发实现
C++完美转发实现
完美转发允许函数模板将参数以原始的值类别(左值或右值)转发给其他函数。这是实现通用包装器和工厂函数的关键技术。
万能引用(转发引用)使用T&&语法,可以绑定到任何值类别。
#include
#include
#include
void process(int& x) {
std::cout << "Lvalue reference: " << x << "\n";
}
void process(int&& x) {
std::cout << "Rvalue reference: " << x << "\n";
}
template
void forward_call(T&& arg) {
process(std::forward(arg));
}
void forwarding_basic() {
int x = 42;
forward_call(x);
forward_call(100);
}
std::forward保持参数的值类别。
template
void wrapper(T&& arg) {
std::cout << "Forwarding...\n";
process(std::forward(arg));
}
完美转发可以实现工厂函数。
template
T* create(Args&&... args) {
return new T(std::forward(args)...);
}
class Widget {
std::string name_;
int value_;
public:
Widget(const std::string& name, int value)
: name_(name), value_(value) {
std::cout << "Widget constructed: " << name_ << ", " << value_ << "\n";
}
Widget(std::string&& name, int value)
: name_(std::move(name)), value_(value) {
std::cout << "Widget move-constructed\n";
}
};
void factory_example() {
std::string name = "test";
Widget* w1 = create(name, 42);
Widget* w2 = create("temp", 100);
delete w1;
delete w2;
}
完美转发可以实现包装器类。
template
class FunctionWrapper {
Func func_;
public:
explicit FunctionWrapper(Func f) : func_(f) {}
template
auto operator()(Args&&... args) {
std::cout << "Before call\n";
auto result = func_(std::forward(args)...);
std::cout << "After call\n";
return result;
}
};
int add(int a, int b) {
return a + b;
}
void wrapper_example() {
FunctionWrapper wrapped(add);
int result = wrapped(10, 20);
std::cout << "Result: " << result << "\n";
}
引用折叠规则决定最终的引用类型。
template
void show_type(T&& arg) {
if (std::is_lvalue_reference::value) {
std::cout << "Lvalue reference\n";
} else if (std::is_rvalue_reference::value) {
std::cout << "Rvalue reference\n";
} else {
std::cout << "Not a reference\n";
}
}
void reference_collapsing() {
int x = 42;
show_type(x);
show_type(100);
}
完美转发在标准库中广泛使用。
#include
#include
void standard_library_forwarding() {
auto ptr = std::make_unique("test", 42);
std::vector vec;
vec.emplace_back("widget1", 10);
vec.emplace_back("widget2", 20);
}
完美转发是现代C++泛型编程的核心技术。
