【Effective Modern Cpp】条款9:优先考虑别名声明而非typedef

  • 别名声明和typedef都能避免使用冗长的变量名称,但是别名声明更加直观,如下:
cpp 复制代码
typedef
    std::unique_ptr<std::unordered_map<std::string, std::string>>
    UPtrMapSS; 
using UPtrMapSS = 
    std::unique_ptr<std::unordered_map<std::string, std::string>>;

typedef void (*FP)(int, const std::string&);
using FP = void (*)(int, const std::string&);
  • 别名声明可以被模板化但是typedef不能,typedef嵌套进模板化的struct才能等效
  • 并且使用typedef声明一个使用了模板形参的对象,必须在typedef前面加上typename
cpp 复制代码
// using
template<typename T>                            
using MyAllocList = std::list<T, MyAlloc<T>>;
MyAllocList<Widget> lw; 

template<typename T> 
class Widget {
private:
    MyAllocList<T> list;
};

// typedef
template<typename T>                            
struct MyAllocList {                            
    typedef std::list<T, MyAlloc<T>> type;
};
MyAllocList<Widget>::type lw;

template<typename T>
class Widget {                              
private:                                    
    typename MyAllocList<T>::type list;
}; 
  • 使用typedef定义的MyAllocList<T>::type是一个依赖类型, 必须使用typename修饰符,避免出现歧义
cpp 复制代码
class Wine { ... };

template<>                 //当T是Wine
class MyAllocList<Wine> {  //特化MyAllocList
private:  
    enum class WineType      
    { White, Red, Rose };

    WineType type;        //在这个类中,type是一个数据成员!
};

说明:如果Widget使用Wine实例化,在Widget模板中的MyAllocList<Wine>::type将会是一个数据成员,不是一个类型,在Widget模板内,MyAllocList<T>::type是否表示一个类型取决于T是什么,这就是为什么编译器会坚持要求你在前面加上typename

相关推荐
艾莉丝努力练剑31 分钟前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
还债大湿兄2 小时前
《C++内存泄漏8大战场:Qt/MFC实战详解 + 面试高频陷阱破解》
c++·qt·mfc
倔强青铜35 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
u_topian5 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
珊瑚里的鱼5 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上6 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
xingshanchang6 小时前
Matlab的命令行窗口内容的记录-利用diary记录日志/保存命令窗口输出
开发语言·matlab
Risehuxyc6 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
AI视觉网奇6 小时前
git 访问 github
运维·开发语言·docker
不知道叫什么呀6 小时前
【C】vector和array的区别
java·c语言·开发语言·aigc