詳解C++泛型裝飾器
更新時間:2021年11月16日 15:54:24 作者:Silent_Blue_Sky
這篇文章主要為大家介紹了C++的泛型裝飾器,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
c++ 裝飾器
本文簡單寫了個 c++ 裝飾器,主要使用的是c++ lamda 表達式,結合完美轉發(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();
}
輸出

對輸出的解釋
左值:表示傳參的過程中調用了拷貝構造函數
右值:表示在傳參過程中調用的是 移動構造函數
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
C++中fstream,ifstream及ofstream用法淺析
這篇文章主要介紹了C++中fstream,ifstream及ofstream用法,適合C++初學者學習文件流的操作,需要的朋友可以參考下2014-08-08
C語言使用stdlib.h庫函數的二分查找和快速排序的實現代碼
以下是對C語言使用stdlib.h庫函數的二分查找和快速排序的實現代碼進行了詳細的介紹,需要的朋友可以過來參考下。希望對大家有所幫助2013-10-10

