How narrow should the declaration be?

I have this little widget class that uses std::string . It uses it in many places, often in combination with std::vector . Thus, you can see that the characters become very long and annoying.

I want to use the using keyword, i.e. using std::string;

The question is, where is the best place to place it?

 // widget.h file #ifndef WIDGET #define WIDGET // (1) namespace example { // (2) namespace nested { // (3) class widget { public: // (4) ... private: // (5) std::string name_; ... }; } } #endif 

My questions:

  • If I put it in (1) , then everyone who includes widget.h will have their area polluted by string ?
  • In places (2) and (3) this is the same story as in 1. only that the namespaces example and example::nested will be polluted in the second file, which includes widget.h ?
  • In places (4) and (5) declaration is quite isolated, but will it be visible in the implementation file (Cpp) and in class inheritance?

Thanks in advance!

+7
source share
1 answer

Do not do this in (1).
Everyone has been cursing your name for a thousand years. As a user of your class, I am not against you polluting your own namespace. But I will be upset if you pollute any of my namespaces (including the global one), as this will affect how my code is compiled. Why is "using namespace std" considered bad practice?

You cannot use it in (4) or (5).

Since I (personally) would like to tie it as close to the point of use as possible (to prevent pollution).
The best you can do is (3).

But I wouldn’t even do that. I am clearly about something from the standard. But I would type the container type.

 private: //(so at 5) Don't need to expose internal details of your class. typedef std::vector<std::string> MyCont; 

This is the best method since you only need to make changes in one place and the changes will be cascaded.

 // Sub typedefs now will no longer need to change if you change // The type of container. Just change the container typedef and // now the iterators are automatically correct. public: //(so at 4) Iterators are public (and not exposing the implementation). typedef MyCont::iterator iterator; typedef MyCont::const_iterator const_iterator; 
+13
source

All Articles