欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解C++泛型装饰器

程序员文章站 2022-03-21 07:57:32
目录c++ 装饰器对输出的解释总结c++ 装饰器本文简单写了个 c++ 装饰器,主要使用的是c++ lamda 表达式,结合完美转发技巧,在一定程度上提升性能#define fieldsetter(n...

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++泛型装饰器

对输出的解释

左值:表示传参的过程中调用了拷贝构造函数

右值:表示在传参过程中调用的是 移动构造函数

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!