【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

相关推荐
ん贤2 小时前
Go channel 深入解析
开发语言·后端·golang
2301_789015624 小时前
DS进阶:AVL树
开发语言·数据结构·c++·算法
Filotimo_5 小时前
5.3 Internet基础知识
开发语言·php
识君啊5 小时前
Java异常处理:中小厂面试通关指南
java·开发语言·面试·异常处理·exception·中小厂
qyzm7 小时前
天梯赛练习(3月13日)
开发语言·数据结构·python·算法·贪心算法
leluckys7 小时前
swift- Swift中常见的面试题
开发语言·汇编·swift
BUG_MeDe7 小时前
json格式字符串解析的简单使用 libjson-c
c语言·开发语言·json
CoderCodingNo8 小时前
【GESP】C++五级练习题 luogu-P1182 数列分段 Section II
开发语言·c++·算法
Qt学视觉8 小时前
AI2-Paddle环境搭建
c++·人工智能·python·opencv·paddle