【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

相关推荐
鲤籽鲲3 小时前
C# Enumerable类 之 数据筛选
开发语言·c#
C#Thread4 小时前
C#上位机--一元运算符
开发语言·c#
正在敲代码中4 小时前
变换队列c++
数据结构·c++·算法
爱跨境的笑笑6 小时前
Skype for Business网络延迟怎么办?
大数据·开发语言·网络·tcp/ip·php
我爱喝伊利7 小时前
C#中使用System.Net库实现自动发送邮件功能
开发语言·c#
NoneCoder7 小时前
JavaScript系列(86)--现代构建工具详解
开发语言·javascript·rust
Zhen (Evan) Wang8 小时前
C#中提供的多种集合类以及适用场景
开发语言·c#
weixin_444009008 小时前
浏览器JS打不上断点,一点就跳到其他文件里。浏览器控制台 js打断点,指定的位置打不上断点,一打就跳到其他地方了。
开发语言·javascript·ecmascript
郑祎亦8 小时前
Java 关键字 volatile
java·开发语言·jvm
BTU_YC8 小时前
Failed to start The PHP FastCGI Process Manager.
开发语言·php