亲宝软件园·资讯

展开

C++ 泛型装饰器 详解C++泛型装饰器

Silent_Blue_Sky 人气:0
想了解详解C++泛型装饰器的相关内容吗,Silent_Blue_Sky在本文为您仔细讲解C++ 泛型装饰器的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C++详解,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();
}

输出

在这里插入图片描述

对输出的解释

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

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

总结

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

加载全部内容

相关教程
猜你喜欢
用户评论