【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

相关推荐
小乖兽技术6 分钟前
在 .NET 8 开发的WinForms 程序中展示程序版本号的几种方式
开发语言·c#·.net
zyhomepage16 分钟前
科技的成就(六十八)
开发语言·人工智能·科技·算法·内容运营
slandarer16 分钟前
MATLAB | R2025a 更新了哪些有趣的东西?
开发语言·matlab
瑞雪兆丰年兮18 分钟前
数学实验(Matlab编程基础)
开发语言·算法·matlab·数学实验
✿ ༺ ོIT技术༻21 分钟前
笔试强训:Day5
c++·算法
努力的小帅36 分钟前
C++_STL_map与set
开发语言·数据结构·c++·学习·leetcode·刷题
yezipi耶不耶1 小时前
Rust入门之高级Trait
开发语言·后端·rust
双叶8361 小时前
(C语言)超市管理系统 (正式版)(指针)(数据结构)(清屏操作)(文件读写)
c语言·开发语言·数据结构·c++·windows
为美好的生活献上中指1 小时前
java每日精进 5.14【参数校验】
java·开发语言·spring boot·tomcat
末央&1 小时前
【数据结构】手撕AVL树(万字详解)
数据结构·c++