C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > c++ 类型别名

c++之类型别名的实现

作者:_DCG_

本文主要介绍了c++之类型别名的实现,包括C++98版本使用typedef关键字和C++11版本推荐使用using关键字来创建类型别名,具有一定的参考价值,感兴趣的可以了解一下

类型别名,顾名思义就是为一个类型创建一个新的名称,使用这个新的名称与使用之前的名称一模一样。

c++98版本的类型别名

c++98版本的类型别名方式使用的是typedef关键字,通过typedef关键字实现的类型别名,下面将展示一些c++98版本的类型别名方式。

//基本类型别名
typedef int Integer;  //不要忘记逗号
typedef unsigned int UInt; //不要忘记逗号

//指针类型别名
typedef int* IntPtr;  //不要忘记逗号
typedef char* CharPtr;  //不要忘记逗号

//函数指针别名
typedef void (*FuncPtr)(int, int);  

//复杂类型别名
typedef std::vector<std::string> StringVector;
typedef std::map<std::string, int> StringIntMap; 

现代c++的类型别名方式

在c++11版本引入了using,通过using实现类型别名,详细的示例如下所示:

//基本类型的类型别名
using Integer = int;
using UInt = unsigned int;

//指针类型的类型别名
using IntPtr = int*;
using CharPtr = char*;

//函数指针的类型别名
using FuncPtr = void(*)(int, int);

//复杂类型的类型别名
using StringVector = std::vector<std::string>;
using StringIntMap = std::map<std::string, int>;

为什么引入using?

之所以引入using作为推荐的类型别名方式,是因为using方式相对于typedef有着明显的优势。

typedef void(*FuncPtr)(int, int);  //typedef形式
using FuncPtr = void(*)(int, int);  //using形式,更直观

typedef不支持模板别名,但是using支持模板别名。请看下面的例子:

// 使用using可以创建模板别名
template<typename T>
using Vec = std::vector<T>;

// 使用示例
Vec<int> numbers;        // 等价于 std::vector<int>
Vec<std::string> words;  // 等价于 std::vector<std::string>

// typedef无法直接实现模板别名,需要额外包装
template<typename T>
struct VectorTypedef {
    typedef std::vector<T> type;
};

常见场景

简化复杂类型

很多时候写一些复杂类型的时候,每次创建该类型的变量或者其他使用该类型的场景,都需要写很长的类型名,通过类型别名,我们可以定义一个简短的名字,后续使用到该类型时,使用这个别名即可。请看下面的例子:

//简化stl容器
using StringSet = std::set<std::string>;
using IntMatrix = std::vector<std::vector<int>>;

// 简化智能指针类型
using StringPtr = std::shared_ptr<std::string>;
using IntUPtr = std::unique_ptr<int>;

回调函数类型

using ErrorCallback = std::function<void(const std::string&)>;
using EventHandler = std::function<void(const Event&)>;

在类中使用类型别名

class Container {
public:
    using value_type = int;
    using pointer = value_type*;
    using reference = value_type&;
    
    // STL风格的类型别名
    using iterator = std::vector<value_type>::iterator;
    using const_iterator = std::vector<value_type>::const_iterator;
private:
    std::vector<value_type> data;
};

注意事项

在c++11及以后的c++版本中推荐使用using,不推荐使用typedef.

到此这篇关于c++之类型别名的实现的文章就介绍到这了,更多相关c++ 类型别名内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文