詳解C++泛型裝飾器
c++ 裝飾器
本文簡(jiǎn)單寫了個(gè) c++ 裝飾器,主要使用的是c++ lamda 表達(dá)式,結(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();
}
輸出

對(duì)輸出的解釋
左值:表示傳參的過程中調(diào)用了拷貝構(gòu)造函數(shù)
右值:表示在傳參過程中調(diào)用的是 移動(dòng)構(gòu)造函數(shù)
總結(jié)
本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Java C++題解leetcode915分割數(shù)組示例
這篇文章主要為大家介紹了Java C++題解leetcode915分割數(shù)組示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
C++實(shí)踐排序函數(shù)模板項(xiàng)目的參考方法
今天小編就為大家分享一篇關(guān)于C++實(shí)踐排序函數(shù)模板項(xiàng)目的參考方法,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-02-02
C++中4種管理數(shù)據(jù)內(nèi)存的方式總結(jié)
根據(jù)用于分配內(nèi)存的方法,C++中有3中管理數(shù)據(jù)內(nèi)存的方式:自動(dòng)存儲(chǔ)、靜態(tài)存儲(chǔ)和動(dòng)態(tài)存儲(chǔ)。在存在時(shí)間的長(zhǎng)短方面,以這三種方式分配的數(shù)據(jù)對(duì)象各不相同。下面簡(jiǎn)要介紹這三種類型2022-09-09
淺析C++字節(jié)對(duì)齊容易被忽略的兩個(gè)問題
今天我就和大家分享一下C++字節(jié)對(duì)齊容易被忽略的兩個(gè)問題。以下問題也是我實(shí)際開發(fā)工作中遇到的,如果有不同意見歡迎交流2013-07-07
C++實(shí)現(xiàn)與Lua相互調(diào)用的示例詳解
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)與Lua相互調(diào)用的方法,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解一下2023-03-03

