在C++中使用"using"关键字

tan*_*anz 6 c++ using c++11

我正在学习C++.我的教授使用了一些类似的代码

using filePath = std::string;
using setOfPaths = std::set<filePath>;
using iterOfSet = setOfPaths::iterator;
using listOfIter = std::list<iterOfSet>;
using iterList = listOfIter::iterator;
using fileName = std::string;
using mapOfFileName = std::map<fileName, listOfIter>;
using iterOfMap = mapOfFileName::iterator;

setOfPaths _setOfPaths;
mapOfFileName _mapOfFileName;
iterOfSet setIter;
Run Code Online (Sandbox Code Playgroud)

我想知道为什么我们使用using关键字.为什么我们不能简单地写

std::string filepath;

std::set<filepath> setOfPaths;
...
...
Run Code Online (Sandbox Code Playgroud)

拥有using关键字有什么好处?

Sho*_*hoe 13

using关键字用于定义类型别名.你的教授使用它的原因是:

  • 可读性
  • 更具描述性
  • 避免不必要的 typename

可读性和描述性

您可以在语义上(并且仅限于)限制特定类型使用类型别名,使名称对特定用途更具描述性.

一个例子是:

using fileName = std::string;
Run Code Online (Sandbox Code Playgroud)

fileName别名是用来描述一个文件名字符串,不是任何字符串.这也使得可读功能签名成为可能.

我觉得我必须再次迭代这个:它只是一个别名.fileName作为参数的任何函数都适用于任何std::string参数.

不必要typename

有些似乎是不必要的,如:

using setOfPaths = std::set<filePath>;
Run Code Online (Sandbox Code Playgroud)

但在某些情况下,它们实际上可以用来避免typename在以下情况下指定:

template<typename Type>
struct something {
    using something_iter = typename std::set<Type>::iterator;
};
Run Code Online (Sandbox Code Playgroud)

有:

template<typename Container>
using itertype = typename Container::iterator;

template<typename Type>
struct something {
    using something_iter = itertype<std::set<Type>>;
}; 
Run Code Online (Sandbox Code Playgroud)

通过移动typename特定的别名,我们可以itertype在多个其他场合重复使用,从而有效避免typename.

关于 typedef

还有另一种定义类型别名的方法:typedef.该关键字继承自C,不允许模板化别名,例如:

template<typename Type>
using vec = std::vector<Type>;
Run Code Online (Sandbox Code Playgroud)

关于类型安全的说明

这实际上不比不使用别名更安全.再次,fileName并且std::string是完全相同的类型.您可以互换使用.

可能的下一步是定义fileName具有其自己的特定不变量的特定类/结构类型.

  • 很好,明确的答案.删除了我的. (2认同)