詳解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é)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
C++中fstream,ifstream及ofstream用法淺析
這篇文章主要介紹了C++中fstream,ifstream及ofstream用法,適合C++初學(xué)者學(xué)習(xí)文件流的操作,需要的朋友可以參考下2014-08-08
C++數(shù)據(jù)結(jié)構(gòu)之哈希算法詳解
這篇文章主要為大家詳細(xì)介紹了C++數(shù)據(jù)結(jié)構(gòu)中哈希算法的相關(guān)資料,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,希望對(duì)大家有所幫助2022-12-12
C語言使用stdlib.h庫(kù)函數(shù)的二分查找和快速排序的實(shí)現(xiàn)代碼
以下是對(duì)C語言使用stdlib.h庫(kù)函數(shù)的二分查找和快速排序的實(shí)現(xiàn)代碼進(jìn)行了詳細(xì)的介紹,需要的朋友可以過來參考下。希望對(duì)大家有所幫助2013-10-10
C++中引用的相關(guān)知識(shí)點(diǎn)小結(jié)
引用是C++一個(gè)很重要的特性,顧名思義是某一個(gè)變量或?qū)ο蟮膭e名,對(duì)引用的操作與對(duì)其所綁定的變量或?qū)ο蟮牟僮魍耆葍r(jià),這篇文章主要給大家總結(jié)介紹了C++中引用的相關(guān)知識(shí)點(diǎn),需要的朋友可以參考下2022-03-03
Qt連接MySQL數(shù)據(jù)庫(kù)的實(shí)現(xiàn)(保姆級(jí)成功版教程)
本文主要介紹了Qt連接MySQL數(shù)據(jù)庫(kù)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
C++ 內(nèi)聯(lián)函數(shù)inline案例詳解
這篇文章主要介紹了C++ 內(nèi)聯(lián)函數(shù)inline案例詳解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09

