C++当命名空间、类名和命名空间::类名冲突时该怎么办

C++ what do do when namespace, classname and namespace::classname clash

本文关键字:命名空间 怎么办 冲突 C++      更新时间:2023-10-16

我继承了一些名字不好的代码,当我收到一个第三方库时,我很幸运,这使我的生活更加复杂。 这就是我最终得到的。

class Something; // third party library
namespace Something {
  class Something;
  class Templated<class TemplateClass>;
}

现在我需要使用第三方库中的类"Something"作为命名空间 Something 下新类的 TemplateClass 参数。 我认为这应该有效

class Something; // third party library
namespace Something {
  class Something;
  class Templated<class TemplateClass>;
  class Impl : public Templated< ::Something > {}
}

但是编译器不喜欢它。 我让它编译的唯一方法是

class Something; // third party library
class Something2 : public Something {} // dirty hack
namespace Something {
  class Something;
  class Templated<class TemplateClass>;
  class Impl : public Templated< Something2 > {}
}

但我真的不喜欢它。 必须有更好的方法来做到这一点。

您可以使用另一个命名空间:

class Something; // third party library
namespace third_party{
  using ::Something;
}
namespace Something {
  class Something;
  class Templated<class TemplateClass>;
  class Impl : public Templated< ::third_party::Something > {}
}

不过,总的来说,我认为将类和命名空间命名完全相同是一个非常糟糕的主意。