typedef 或在我的命名空间中公开外部库类时使用的 using 关键字

typedef or using keyword when exposing external library class in my namespace

本文关键字:关键字 using 外部 我的 命名空间 typedef      更新时间:2023-10-16

我想向我的库用户公开外部库中的类。 具体来说,我想将类"导入"到我的命名空间,这样用户就不需要知道我在幕后使用了哪些库。 通常,我似乎可以通过使用typedef来做到这一点,或者简单地using类。 有什么理由选择一种方法而不是另一种方法(或做其他事情)吗? (我的教育:)似乎有一些差距)

例如:我想创建一个使用 Boost::Asio 的串行端口管理器。

namespace MySerialManager {
  //should I use a typedef
  typedef boost::asio::serial_port_base::flow_control flow_control ;
  //or a using...
  using boost::asio::serial_port_base::flow_control;
  class SerialManager 
  {
    //let the user specifify the flow on construction
    SerialManager(const flow_control& fc);
  }
}

或者我应该完全做别的事情...... 非常感谢。

两者具有相同的最终结果。 使用可能更接近您的意图。

如果你想"导入"一个类模板,那么using将是你唯一的选择。就目前而言,我认为没有任何实质性差异。就个人而言,在上述情况下,我会选择typedef,因为它是一个更古老,更熟悉的结构。