詳解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();
}

輸出

在這裡插入圖片描述

對輸出的解釋

左值:表示傳參的過程中調用瞭拷貝構造函數

右值:表示在傳參過程中調用的是 移動構造函數

總結

本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!

推薦閱讀: