Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

root namespace coding convention in C++

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.

like image 445
moala Avatar asked Mar 23 '11 11:03

moala


2 Answers

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;
    }
}
like image 53
Konrad Rudolph Avatar answered Oct 03 '22 16:10

Konrad Rudolph


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.

like image 20
trenki Avatar answered Oct 03 '22 16:10

trenki