When implementing a function in CPP, I am used to put my helper functions in an anonymous namespace, so they don't pollute the global namespace outside the CPP file where they are defined.
However, the same doesn't seem to apply to using
declarations? I.e., it seems that I can put them outside the anomymous namespace, and they still don't leak to the global namespace. What is special about them?
In the following example, I feel I should I put using std::cout
in the anonymous namespace to avoid polluting the global namespace. But things are also fine as they are: attempting to use cout
in main.cpp
errors.
myHeader.hpp
#pragma once
namespace myNamespace {
void print (int);
}
mySource.cpp
#include <iostream>
#include "myHeader.hpp"
namespace {
// I need to put helperFunction here so it is only visible in this file.
void helperFunction () { /*Do stuff ...*/ }
}
// This declaration only applies to this file as if it were in the anonymous namespace. How?
using std::cout;
void myNamespace::print (int value) {
helperFunction();
cout << value << std::endl;
}
myMain.cpp
#include <iostream>
#include "myHeader.hpp"
int main () {
myNamespace::print(42);
// helperFunction(); // This would error.
// cout << 42; // I want this to error too.
return 0;
}