简体   繁体   English

具有名称空间的内部功能是否不好?

[英]Is it bad code to have internal functions for namespaces

Say I have a namespace Util, which contains some basic functions. 假设我有一个名称空间Util,其中包含一些基本功能。 But in that namespace I need the functionality of a library to do my work, however I don't want the header file to know about it so I end up making an anonymous namespace with the functionality that I need but don't want exposed. 但是在该名称空间中,我需要一个库的功能来完成工作,但是我不想让头文件知道它,因此最终我使用所需的功能创建了一个匿名的名称空间,但又不想将其公开。 Is there a better way to do this ? 有一个更好的方法吗 ?

As an example: 举个例子:

# Util.h  
namespace Util{  int Add();  }

# Util.cpp
namespace Util{
 namespace {
  funkyInt Add_internal(int x, int y);
  int convert(funkyInt x);
 }

 int Add(int x, int y){
  return convert(Add_internal(x,y))
 }

 funkyInt Add_internal(int x, int y){
 //DOSomething
 }
}

That's perfectly fine. 很好

Whether the anonymous namespace is in your namespace or the global one is taste and ease. 匿名命名空间是在您的命名空间中还是在全局命名空间中,是一种品味和轻松。

  • Taste, because the code may be exactly identical 品味,因为代码可能完全相同
  • Ease because if you reuse other function of your non anonymous namespace, you don't have to prefix or use the namespace. 放宽,因为如果您重复使用非匿名名称空间的其他功能,则不必添加前缀或使用名称空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM