root namespace coding convention in C++

牧云@^-^@ 提交于 2019-12-21 10:29:52

问题


Would you recommand prefixing global namespaces with ::? (for instance ::std::cout instead of std::cout) Why? Is it faster to parse for the C++ compiler?

Thanks.


回答1:


Only do this to disambiguate.

I have a piece of code where this is necessary since I’m in a namespace X which has a function for a standard deviation – std. Whenever I want to access the std namespace, I need to use ::std because otherwise the compiler will think that I am referring to said function.

Concrete example:

namespace X {
    double std(::std::vector<double> const& values) { … }

    void foo(::std::vector<double> const& values) {
        ::std::cout << std(values) << ::std::endl;
    }
}



回答2:


It has nothing to do with parsing speed. C++ uses Argument-dependent name lookup - Koenig Lookup and when you have to make sure that the compiler uses the symbol from the global root namespace you prefix it with ::. If you don't the compiler might also use function definitions from other namespaces when it sees fit (depending on the lookup method).

So, it is better not to do it unless you have to.




回答3:


You don't need to, as the compiler will

a) find it anyway b) output an error if there are any ambiguations, like

namespace foo
{
  int test()
  {
    return 42;
  }
}

namespace bar
{
  namespace foo
  {
    int test()
    {
      return 42;
    }
  }
}

int main()
{
  using namespace bar;
  return foo::test(); // error, could be ::foo::test or ::bar::foo::test
}



回答4:


Don't do that. It clutters your code and disables the option to implement a self-made variant of the functions you are using.




回答5:


I cannot see any good reason to do this. It makes the code less readable, and should only be used when you explicitly must tell the compiler to use the root namespace. Like when there is ambiguities.



来源:https://stackoverflow.com/questions/5404834/root-namespace-coding-convention-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!