Should it be in the namespace?

Should I put the code from .cpp into the namespace from the corresponding .h or is it enough to just write with the declaration?

//file .h namespace a { /*interface*/ class my { }; } //file .cpp using a::my; // Can I just write in this file this declaration and // after that start to write implementation, or // should I write: namespace a //everything in a namespace now { //Implementation goes here } 

Thanks.

+6
c ++ namespaces
source share
3 answers

I find it more appropriate to surround all the code that should be in the namespace in the namespace a { ... } block, since this is semantically what you do: you define the elements in the namespace a . But if you only identify participants, then both things will work.

When the compiler finds void my::foo() , it will try to determine that my , and find using a::my , allow my from this and understand that you are defining a::my::foo method.

On the other hand, this approach will fail if you use free functions:

 // header namespace a { class my { // ... }; std::ostream & operator<<( std::ostream& o, my const & m ); } // cpp using a::my; using std; ostream & operator<<( ostream & o, my const & m ) { //.... } 

The compiler will happily translate the above code into the program, but what it actually does declares std::ostream& a::operator<<( std::ostream&, a::my const & ) in the header file - without implementation - and defines std::ostream& ::operator<<( std::ostream &, a::my const & ) in the cpp file, which is another function. Using a Koening search, whenever the compiler sees cout << obj with an obj type a::my , the compiler will look in the enclosing name spaces cout and my ( std and a ) and find that there is a::operator<< declared, but not defined in namespace a . It will compile but not link your code.

+4
source share

If I understand the question correctly, you can just use :: my and then just implement methods like

 using a::my; void my::doSomething() {} 
+1
source share

Can you do this. But, right?

This is an unusual practice, and it is likely to lead to a distribution using a::Type; for each type from the namespace 'a' used in the .cc file. Is this good for you, but I voted against it :)

0
source share

All Articles