下面是《深入理解c++11》中的部分截图
以下是自己的实现,实用几个宏,实现对多用类成员变量的setter和getter,auto与decltype搭配,干活不累
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36#define GetProperty(Var,VarName) inline auto Get##VarName() const ->decltype(Var) { return Var;} #define SetProperty(Var,VarName) inline void Set##VarName(decltype(Var) _v){ Var = _v;} #define GetSetProperty(Var,VarName) GetProperty(Var, VarName) SetProperty(Var, VarName) //decltype(Var) 根据Var实际的类型推导出类型 class Pig { private: int mAge; std::string mName; public: GetSetProperty(mAge, Age); //一定要在声明的变量名下面(有点习惯性的把方法写在上面,变量在下面),不然编译报错,未定义mAge GetSetProperty(mName, Name); }; void testDeclType() { int iarr[10] = { 0 }; decltype(iarr) ib; //这个时候ib的定义等价于 int ib[10];两者是一样的,不要认为ib是一个指针了,它是一个正宗的数组。 printf("--- sizeof ib:%dn",sizeof(ib)); //40 Pig p; p.SetAge(123); p.SetName("uuu"); printf("--- pig age:%d, name:%sn",p.GetAge(), p.GetName().c_str()); /* --- sizeof ib:40 --- pig age:123, name:uuu */ }
最后
以上就是呆萌高跟鞋最近收集整理的关于c++11中decltype的妙用的全部内容,更多相关c++11中decltype内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复