Is there any way to avoid fully-specified class-names in a header without namespace pollution?

Viewed 92

We have a lot of classes not in any namespace, which use std extensively.

e.g.:

class MyClass
{
std::map<std::string,std::vector<std::string>> mLookup
...

This is tedious but because it's a header I cannot just do using namespace std; or I will cause awful pollution.

Neither can I (I think) move this class into a new namespace without then having to update every use of it in the rest of the codebase, which is all starting to get a bit of a serious task.

So I want to check, C++(17) does not provide any other solution? I just need to fully-specify things or introduce namespaces?

2 Answers

No, you don't have to change everything if you:

  1. Have a collection of classes that you wish to move into a specific namespace

  2. Your code is well-organized, and those classes are implemented in their own, distinct, translation units, that are separate from all other classes.

The only thing that needs to be done:

A) In your header files simply move the classes in their own namespace declaration:

#ifndef myclass_h
#define myclass_h

namespace app {   // start of namespace declaration
#if 0
}
#endif

class MyClass {
public:
    MyClass();

// ...

#if 0
{
#endif
}          // End of namespace declaration

#endif

This preprocessor trick even eliminates the need to reindent everything, and fool syntax-aware code editors into not adding an extra level of indentation. All references from MyClass to other classes that get transplanted into the new namespaces, together, get updated as well (provided that their header files are adjusted the same way).

B) Finally, the same thing gets done in every translation unit.

#include "myclass.H"

namespace app {
#if 0
}
#endif

MyClass::MyClass()
{
   /// ...


#if 0
{
#endif
}

And now, with just a few minutes of typing you moved a bunch of classes into a new namespace.

P.S. In a couple of years your fingers will automatically type "std::" without you even being consciously aware of it, so that'll become a non-issue.

From looking further the short answer is: NO.

You can employ using a::b::c within methods or functions defined in header files and you can of course use namespaces in your .cpp files, but there is no way to do this in a header without polluting the codebase.

The proper way is to move things into namespaces but the question specifically asks for alternatives... seems there aren't really any. A lesson when writing new code to avoid this pitfall in future"

Related