【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

相关推荐
2501_944521592 小时前
Ramda 跨端三方库仓颉适配全流程
开发语言·javascript·flutter·php
行思理2 小时前
go语言学习难度及适合学习的人群
开发语言·学习·golang
青瓦梦滋2 小时前
WebSocket协议
linux·服务器·网络·c++·websocket·网络协议·http
wangchunyu1143 小时前
JAVA CompletableFuture异步编程实战
java·开发语言·python
程序 代码狂人4 小时前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
meiying88386 小时前
快递单号批量查询Python脚本:从手动到自动化的完整实现
开发语言·python·自动化
@大迁世界6 小时前
告别 Go,拥抱 Rust
开发语言·golang·rust
SEO_juper6 小时前
Node.js 重定向链检测工具:301 跳了几跳、有没有成环,一次看清
xml·开发语言·python·node.js·json·bash
学逆向的6 小时前
C 指针常量与常量指针
c语言·开发语言·网络安全
低调滴开发7 小时前
3 行代码写崩一个函数?切片才是 Rust 字符串处理的正确姿势
开发语言·后端·rust