栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ 泛型装饰器

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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(hargs)...);
        return [f = std::move(tail)](auto &&...args) {
            return f(forward(args)...);
        };
    };

    auto nameWithAge = withDecorator(Object, Age, ObjectField("nic"));
    auto withDecoratorWithSex = withDecorator(nameWithAge, sex, AgeField(18));
    withDecoratorWithSex(SexField("man"));
}

int main() {
    DecoratorTest();
}
输出


对输出的解释
[左值 ] 表示传参的过程中调用了拷贝构造函数
[右值 ] 表示在传参过程中调用的是 移动构造函数

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/511841.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号