It is widely known that adding declarations/definitions to namespace std results in undefined behavior. The only exception to this rule is for template specializations.
What about the following “hack”?
#include <iostream>
namespace std_
{
void Foo()
{
std::clog << "Hello World!" << std::endl;
}
using namespace std;
}
int main()
{
namespace std = std_;
std::Foo();
}
Is this really well-defined as far as the standard is concerned? In this case, I’m really not adding anything to namespace std, of course. Every compiler I’ve tested this on seems to happily swallow this.
Before someone makes a comment resembling “why would you ever do that?” — this is just to satisfy my curiosity…
Redefining
stdas an alias is okay, as long as you are not in the global declarative region:Since you define the alias in
main(), it shadows the globalstdname. That’s why this works, should work, and is perfectly fine according to the standard. You’re not adding anything to thestdnamespace, and this “hack” only serves to confuse the human reader of the code.