C++如何实现泛型装饰器

发布时间:2021-11-16 17:17:44 作者:小新
来源:亿速云 阅读:176

小编给大家分享一下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++如何实现泛型装饰器

对输出的解释

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

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

以上是“C++如何实现泛型装饰器”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. python装饰器的原理--装饰器过程
  2. 如何实现classmethod装饰器?

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:Golang开发库有哪些

下一篇:如何深入理解JavaScript错误和堆栈追踪

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》