{"id":336,"date":"2018-02-14T06:50:37","date_gmt":"2018-02-14T06:50:37","guid":{"rendered":"http:\/\/cppdepend.com\/blog\/?p=336"},"modified":"2018-11-09T18:32:57","modified_gmt":"2018-11-09T18:32:57","slug":"7-common-reasons-of-using-the-namespaces-in-a-c-project","status":"publish","type":"post","link":"https:\/\/cppdepend.com\/blog\/7-common-reasons-of-using-the-namespaces-in-a-c-project\/","title":{"rendered":"7 Common reasons of using the namespaces in a C++ project."},"content":{"rendered":"<p>Namespaces were introduced to the C++ Standard in 1995\u00a0and usually they are defined like this:<\/p>\n<blockquote><p>A namespace defines a new scope. They provide a way to avoid name collisions.<\/p><\/blockquote>\n<p>Although namespaces are used extensively in recent C++ code, most older code does not use this facility.\u00a0<span id=\"more-1071\"><\/span><\/p>\n<p>After exploring the source code of many C++ projects, here are some common reasons of using the namespaces in these projects.<!--more--><\/p>\n<h2>1- Avoid\u00a0name collisions.<\/h2>\n<p>In this case their use are\u00a0just useful for the compiler, no added value for the developer to make the code more readable and maintainable.<\/p>\n<h2><strong>2- Modularize the\u00a0code<\/strong><\/h2>\n<p>Modern C++ libraries use extensively the namespaces to modularize their code base, and they use the \u00a0\u201cNamespace-by-feature\u201d approach.\u00a0Namespace-by-feature uses namespaces\u00a0to reflect the feature set. It places all items related to a single feature (and only that feature) into a single namespace. This results in namespaces\u00a0with high cohesion and high modularity, and with minimal coupling between namespaces. Items that work closely together are placed next to each other.<\/p>\n<p>Boost is the best example of grouping by feature, it contains thousands of namespaces, each one is used to group a specific feature.<\/p>\n<h2><strong>3- Anonymous namespace.<\/strong><\/h2>\n<p>Namespace with no name avoids making global static variable. The \u201canonymous\u201d namespace you have created will only be accessible within the file you created it in.<\/p>\n<h2>4- workarround of the enum issue.<\/h2>\n<p>\u201cTraditional\u201d enums in C++ export their enumerators in the surrounding scope ,which can lead to name collisions, if two different enums in the same have scope define enumerators with the same name,<\/p>\n<p>In a large project, you would not be guaranteed that two distinct enums don\u2019t both called with the same name. This issue was resolved in C++11, using\u00a0\u00a0<strong>enum class<\/strong>\u00a0which will implicitly scope the enum values within the enum\u2019s name.<\/p>\n<p>Many years ago the trick of declaring an enum inside a namespace is used, for example instead of declaring an enum like this<\/p>\n<pre class=\"lang-cpp prettyprint prettyprinted\"><code><span class=\"kwd\">enum<\/span><span class=\"pln\"> status<\/span><span class=\"pun\">{<\/span><span class=\"pln\">\r\n  status_ok<\/span><span class=\"pun\">,<\/span><span class=\"pln\">\r\n  status_error\r\n<\/span><span class=\"pun\">};<\/span><\/code><\/pre>\n<p>it\u2019s declared inside an namespace:<\/p>\n<pre class=\"lang-cpp prettyprint prettyprinted\"><code><span class=\"kwd\">namespace<\/span><span class=\"pln\"> status<\/span><span class=\"pun\">{\r\n<\/span><span class=\"kwd\">       enum<\/span><span class=\"pln\"> status<\/span><span class=\"pun\">{<\/span><span class=\"pln\">\r\n         ok<\/span><span class=\"pun\">,<\/span><span class=\"pln\">\r\n          error\r\n  <\/span><span class=\"pun\">};\r\n<\/span><span class=\"pun\">}<\/span><\/code><\/pre>\n<p>Many C++ projects use this trick, for example the Unreal Engine source code use widely this technique.<\/p>\n<p>[adrotate banner=&#8221;3&#8243;]<\/p>\n<h2><strong>5- Hiding details by convention<\/strong><\/h2>\n<p>For templated libraries where the code is implemented in header files, it\u2019s\u00a0interesting to find a way to inform the library user that he do not need to use directly some specific types because they concern only the implementation.\u00a0In\u00a0C# the \u201cinternal\u201d keyword did the job, but in C++ there\u2019s no way to hide public types to the library user.<\/p>\n<p>A common idiom in modern C++, pioneered by the developers of the Boost libraries, is to separate symbols that form part of the implementation of your module (that is, don\u2019t form part of the public API) but that have to be publicly available into a separate sub-namespace, by convention named detail.<\/p>\n<p>For example in the boost::math documentation, it\u2019s specified that:<\/p>\n<blockquote><p>Functions not intended for use by applications are in\u00a0<code class=\"computeroutput\"><span class=\"identifier\">boost<\/span><span class=\"special\">::<\/span><span class=\"identifier\">math<\/span><span class=\"special\">::<\/span><span class=\"identifier\">detail<\/span><\/code>.<\/p><\/blockquote>\n<div class=\"body refbody\">\n<div class=\"section\">\n<h2 class=\"title sectiontitle ibm-h3 ibm-padding-top-1\">And the inline namespaces provided by C++11 brings two other possibilities:<\/h2>\n<div class=\"p ibm-padding-bottom-1\">\n<p class=\"p\">When an inline namespace is defined, a\u00a0<samp class=\"ph codeph\">using<\/samp>\u00a0directive is implicitly inserted into its enclosing namespace. While looking up a qualified name through the enclosing namespace, members of the inline namespace are brought in and found by the implicit\u00a0<samp class=\"ph codeph\">using<\/samp>\u00a0directive, even if that name is declared in the enclosing namespace.<\/p>\n<div class=\"p ibm-padding-bottom-1\">\n<p>For example, if you compile the following code with USE_INLINE_B defined, the output of the resulting executable is 1; otherwise, the output is 2.<\/p>\n<pre class=\"pre codeblock\" data-clipboard-id=\"codeblock0\">namespace A {\r\n#if USE_INLINE_B\r\n\u00a0\u00a0 inline\r\n#endif\r\n\u00a0\u00a0 namespace B {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0 int foo(bool) { return 1; }\r\n\u00a0\u00a0 }\r\n\u00a0\u00a0 int foo(int) { return 2; }\r\n}\r\n\r\nint main(void) {\r\n\u00a0\u00a0 return A::foo(true);\r\n}<\/pre>\n<\/div>\n<p>Here are the two other possibilities of using the inline namespaces as explained in\u00a0this <a href=\"https:\/\/www.ibm.com\/support\/knowledgecenter\/en\/SSLTBW_2.2.0\/com.ibm.zos.v2r2.cbclx01\/namespace_association.htm\">document<\/a>.<\/p>\n<p>[adrotate banner=&#8221;3&#8243;]<\/p>\n<h2>6-Using inline namespace definitions in explicit instantiation and specialization<\/h2>\n<p>You can explicitly instantiate or specialize each member of an inline namespace as if it were a member of its enclosing namespace. Name lookup for the primary template of an explicit instantiation or specialization in a namespace, for example M, considers the inline namespaces whose enclosing namespace set includes M. For example:<\/p>\n<pre class=\"pre codeblock\" data-clipboard-id=\"codeblock2\">namespace L {\r\n   inline namespace M {\r\n       template &lt;typename T&gt; class C; \r\n   }\r\n\r\n   template &lt;typename T&gt; void f(T) { \/*...*\/ };\r\n}\r\n\r\nstruct X { \/*...*\/ };\r\nnamespace L {\r\n  template&lt;&gt; class C&lt;X&gt; { \/*...*\/ };    \/\/template specialization\r\n}\r\n\r\nint main()\r\n{\r\n  L::C&lt;X&gt; r;\r\n  f(r);  \/\/ fine, L is an associated namespace of C\r\n}<\/pre>\n<p>In this example,\u00a0<samp class=\"ph codeph\">M<\/samp>\u00a0is an inline namespace of its enclosing namespace\u00a0<samp class=\"ph codeph\">L<\/samp>, class\u00a0<samp class=\"ph codeph\">C<\/samp>\u00a0is a member of inline namespace\u00a0<samp class=\"ph codeph\">M<\/samp>, so\u00a0<samp class=\"ph codeph\">L<\/samp>\u00a0is an associated namespace of class\u00a0<samp class=\"ph codeph\">C<\/samp>.<\/p>\n<\/div>\n<div class=\"p ibm-padding-bottom-1\">\n<p>The following rules apply when you use inline namespace definitions in explicit instantiation and specialization:<\/p>\n<ul class=\"ul ibm-colored-list ibm-textcolor-gray-80\">\n<li class=\"li\">An explicit instantiation must be in an enclosing namespace of the primary template if the template name is qualified; otherwise, it must be in the nearest enclosing namespace of the primary template or a namespace in the enclosing namespace set.<\/li>\n<li class=\"li\">An explicit specialization declaration must first be declared in the namespace scope of the nearest enclosing namespace of the primary template, or a namespace in the enclosing namespace set. If the declaration is not a definition, it may be defined later in any enclosing namespace.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<div class=\"section\">\n<h2 class=\"title sectiontitle ibm-h3 ibm-padding-top-1\">7-Using inline namespace definitions in library versioning<\/h2>\n<p class=\"p\">With inline namespace definitions, you can provide a common source interface for a library with several implementations, and a user of the library can choose one implementation to be associated with the common interface. The following example demonstrates the use of inline namespace in library versioning with explicit specialization.<\/p>\n<div class=\"p ibm-padding-bottom-1\">\n<pre class=\"pre codeblock\" data-clipboard-id=\"codeblock3\">\/\/foo.h\r\n#ifndef SOME_LIBRARY_FOO_H_\r\n   #define SOME_LIBRARY_FOO_H_\r\n   namespace SomeLibrary\r\n   {\r\n      #ifdef SOME_LIBRARY_USE_VERSION_2_\r\n         inline namespace version_2 { }\r\n      #else    \r\n      \t  inline namespace version_1 { }\r\n      #endif\r\n      namespace version_1 {\r\n       \t template &lt;typename T&gt; int foo(T a) {return 1;}\r\n      }     \r\n      namespace version_2 {\r\n       \t template &lt;typename T&gt; int foo(T a) {return 2;}\r\n      }\r\n   }  \r\n#endif \r\n\r\n\/\/myFooCaller.C \r\n#include &lt;Foo.h&gt;\r\n#include &lt;iostream&gt;\r\n\r\nstruct MyIntWrapper { int x;}; \r\n\r\n\/\/Specialize SomeLibrary::foo()\r\n\/\/Should specialize the correct version of foo()\r\n\r\nnamespace SomeLibrary {\r\n\t  template &lt;&gt; int foo(MyIntWrapper a) { return a.x;}\r\n}\r\n\r\nint main(void) {\r\n\t  using namespace SomeLibrary;\r\n\t  MyIntWrapper intWrap = { 4 };\r\n\t  std::cout &lt;&lt; foo(intWrap) + foo(1.0) &lt;&lt; std::endl;\r\n}<\/pre>\n<p>If you compile this example with SOME_LIBRARY_USE_VERSION_2_ defined, the output of the resulting executable is 6; otherwise, the output is 5. If the function call,\u00a0<samp class=\"ph codeph\">foo(intWrap)<\/samp>, is qualified with one of the inline namespaces, then you need to ensure that the explicit specialization is effective.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p>[adrotate banner=&#8221;3&#8243;]<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Namespaces were introduced to the C++ Standard in 1995\u00a0and usually they are defined like this: A namespace defines a new scope. They provide a way to avoid name collisions. Although namespaces are used extensively in recent C++ code, most older code does not use this facility.\u00a0 After exploring the source code of many C++ projects, &hellip; <a href=\"https:\/\/cppdepend.com\/blog\/7-common-reasons-of-using-the-namespaces-in-a-c-project\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;7 Common reasons of using the namespaces in a C++ project.&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[13,41],"class_list":["post-336","post","type-post","status-publish","format-standard","hentry","category-uncategorized","tag-cpp","tag-namespaces"],"_links":{"self":[{"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts\/336","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/comments?post=336"}],"version-history":[{"count":12,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts\/336\/revisions"}],"predecessor-version":[{"id":1209,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/posts\/336\/revisions\/1209"}],"wp:attachment":[{"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/media?parent=336"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/categories?post=336"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cppdepend.com\/blog\/wp-json\/wp\/v2\/tags?post=336"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}