这篇文章主要为大家介绍了C++的泛型装饰器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
c++ 装饰器
本文简单写了个 c++ 装饰器,主要使用的是c++ lamda 表达式,结合完美转发技巧,在一定程度上提升性能
#define FieldSetter(name, type, field) \
type field; \
name() {} \
name(const type& field): field(field) { \
cout << "[左值 " << field << "]" << endl; \
} \
name(const type&& field) : field(move(field)){ \
cout << "[右值 " << field << "]" << endl; \
} \
name(const name& other) { \
field = other.field; \
cout << "[左值 " << other.field << "]" << endl; \
} \
name(const name&& other) { \
field = move(other.field); \
cout << "[右值 " << other.field << "]" << endl; \
}
struct ObjectField {
FieldSetter(ObjectField, string, name);
};
struct AgeField {
FieldSetter(AgeField, int, age);
};
struct SexField {
FieldSetter(SexField, string, sex);
};
void DecoratorTest() {
auto Object = [](auto ob) {
cout << ob.name << endl;
};
auto Age = [](auto age) {
cout << age.age << endl;
};
auto sex = [](auto sex) {
cout << sex.sex << endl;
};
auto withDecorator = [](auto &&head, auto &&tail, auto &&...hargs) {
head(forward<decltype(hargs)>(hargs)...);
return [f = std::move(tail)](auto &&...args) {
return f(forward<decltype(args)>(args)...);
};
};
auto nameWithAge = withDecorator(Object, Age, ObjectField("nic"));
auto withDecoratorWithSex = withDecorator(nameWithAge, sex, AgeField(18));
withDecoratorWithSex(SexField("man"));
}
int main() {
DecoratorTest();
}
输出
对输出的解释
左值:表示传参的过程中调用了拷贝构造函数
右值:表示在传参过程中调用的是 移动构造函数
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程学习网的更多内容!
沃梦达教程
本文标题为:详解C++泛型装饰器
猜你喜欢
- Qt计时器使用方法详解 2023-05-30
- C语言qsort()函数的使用方法详解 2023-04-26
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- C++ 数据结构超详细讲解顺序表 2023-03-25
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- ubuntu下C/C++获取剩余内存 2023-09-18
- C语言详解float类型在内存中的存储方式 2023-03-27
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- Easyx实现扫雷游戏 2023-02-06