在接口头文件中使用typedef是一个不好的做法吗?

Is it a bad practice to use typedef in interface header file?

本文关键字:一个 文件 接口 typedef      更新时间:2023-10-16

我知道在头文件中使用"using namespace xxx"是一个不好的做法,但是在接口头文件中使用typedef呢?

例如:

typedef std::set<unsigned int> rsids_type;    //!< typedef something.
struct IRsids 
{
    virtual const rsids_type& GetRsids() = 0;
}

在我的选择,我认为这也是一个坏的做法,我们导入一个名称"rsids_type"到全局命名空间?那么下面的动作呢?

struct IRsids 
{
    typedef std::set<unsigned int> rsids_type;    //!< typedef something inside the interface class.
    virtual const rsids_type& GetRsids() = 0;
}

使用typedef不必要地污染全局命名空间是语言允许的,但显然不受惯例的鼓励。

名称空间在这里(以及其他东西)是为了避免名称冲突,因此将类型定义放在名称空间和/或类中(如第二个示例)。

typedefs通常放在头文件中,通常用作封装的一种手段(在简单的名称后面隐藏复杂的类型),例如:

typedef std::vector<std::vector<double>> Matrix

标准库实现在所有地方都这样做。

注意:

  • using namespace应该避免在头文件中出现,因为任何头文件的包含都会带来整个命名空间。这不是typedef的情况,它基本上是一个类型别名,所以没有问题。
  • 在c++ 11中,typedef s和using别名是等价的:

的例子:

using Matrix = std::vector<std::vector<double>>;

相关文章: