In C++, it is very much customary to avoid using
namespaces in header files, for several reasons.
Unlike C#, C++ doesn't have a nice tidy module system. Anything you do in a header affects every file which includes it. So if one header has a using namespace
, if effectively pollutes not just the header file itself, but all files which include it. That can lead to surprising name clashes.
So in C++, the most common convention is this: never put using namespace
in a header. In source files, you can do it if you want to, but many people avoid it even there.
Another reason is that this can actually aid readability:
If I refer to a vector<int>
, it's not really clear what that is. It could be any vector class defined anywhere in any of my included headers.
But if I write std::vector<int>
, then I know that this is the standard library header. It tells me where a type comes from. I think that makes the code both clearer and more easy to read.
Of course, there are tricks you can use to make this more manageable, if you refer to certain types a lot, or if certain namespaces have long, verbose names.
Long namespace names can be aliased:
namespace foo = VeryLongNamespaceName;
// now I can do foo::bar instead of VeryLongNamespaceName::bar
or individual names can be imported from a namespace:
using std::cout;
// now I can refer to `cout` without the std prefix
Of course, it is not a coincidence that C++ developers tend to use flat namespace hierarchies and short namespace names.
Nearly all of the C++ standard library is in the std
namespace, which is a bit easier to type than the .NET equivalent. (std::vector<T>
vs System.Collections.Generic.List<T>
). Short names and a flat hierarchy means that you can actually live without using namespace
statements.
Can anyone give me a definitive explanation of this issue as it related to the Winrt world (im not interested in c++ in other environments)
There is no such thing as "the WinRT world" in this context. If you write C++ code in your WinRT application, then you should follow C++ conventinos and best practices. If you write C# code in your WinRT application, then you should follow C# best practices, and so on.
Nowhere do WinRT guidelines state "please disregard everything you would normally do in the language you're using". WinRT is an API, not a language.
As for why Microsoft's samples do otherwise: they're samples. Their goal is to illustrate specific concepts and give you a starting point, and not to teach you to write good code in general. It is assumed that you can take the concepts they illustrate, and fit it into your own code without copying the various shortcuts taken in the samples. Many samples also omit error handling code for the same reason. It's irrelevant for the purposes of the sample, but certainly not irrelevant in a real application.