詳解C++泛型裝飾器
更新時間:2021年11月16日 15:54:24 作者:Silent_Blue_Sky
這篇文章主要為大家介紹了C++的泛型裝飾器,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
c++ 裝飾器
本文簡單寫了個 c++ 裝飾器,主要使用的是c++ lamda 表達式,結(jié)合完美轉(zhuǎn)發(fā)技巧,在一定程度上提升性能
#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(); }
輸出
對輸出的解釋
左值:表示傳參的過程中調(diào)用了拷貝構(gòu)造函數(shù)
右值:表示在傳參過程中調(diào)用的是 移動構(gòu)造函數(shù)
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Java C++題解leetcode915分割數(shù)組示例
這篇文章主要為大家介紹了Java C++題解leetcode915分割數(shù)組示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11C++中4種管理數(shù)據(jù)內(nèi)存的方式總結(jié)
根據(jù)用于分配內(nèi)存的方法,C++中有3中管理數(shù)據(jù)內(nèi)存的方式:自動存儲、靜態(tài)存儲和動態(tài)存儲。在存在時間的長短方面,以這三種方式分配的數(shù)據(jù)對象各不相同。下面簡要介紹這三種類型2022-09-09C++實現(xiàn)與Lua相互調(diào)用的示例詳解
這篇文章主要為大家詳細介紹了C++實現(xiàn)與Lua相互調(diào)用的方法,文中的示例代碼講解詳細,具有一定的學(xué)習(xí)價值,感興趣的小伙伴可以了解一下2023-03-03