Why and how should I use namespaces in C++?












26















I have never used namespaces for my code before. (Other than for using STL functions)




  1. Other than for avoiding name conflicts, is there any other reason to use namespaces?

  2. Do I have to enclose both declarations and definitions in namespace scope?










share|improve this question



























    26















    I have never used namespaces for my code before. (Other than for using STL functions)




    1. Other than for avoiding name conflicts, is there any other reason to use namespaces?

    2. Do I have to enclose both declarations and definitions in namespace scope?










    share|improve this question

























      26












      26








      26


      8






      I have never used namespaces for my code before. (Other than for using STL functions)




      1. Other than for avoiding name conflicts, is there any other reason to use namespaces?

      2. Do I have to enclose both declarations and definitions in namespace scope?










      share|improve this question














      I have never used namespaces for my code before. (Other than for using STL functions)




      1. Other than for avoiding name conflicts, is there any other reason to use namespaces?

      2. Do I have to enclose both declarations and definitions in namespace scope?







      c++ namespaces






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 18 '10 at 5:02









      nakiyanakiya

      6,409175699




      6,409175699
























          6 Answers
          6






          active

          oldest

          votes


















          12














          Here is a good reason (apart from the obvious stated by you).



          Since namespace can be discontiguous and spread across translation units, they can also be used to separate interface from implementation details.



          Definitions of names in a namespace can be provided either in the same namespace or in any of the enclosing namespaces (with fully qualified names).






          share|improve this answer


























          • Link seems dead or down.

            – Alex
            Jan 16 at 9:33











          • The link seems to work for me.

            – Giselle Serate
            Jan 30 at 5:39



















          23














          One reason that's often overlooked is that simply by changing a single line of code to select one namespaces over another you can select an alternative set of functions/variables/types/constants - such as another version of a protocol, or single-threaded versus multi-threaded support, OS support for platform X or Y - compile and run. The same kind of effect might be achieved by including a header with different declarations, or with #defines and #ifdefs, but that crudely affects the entire translation unit and if linking different versions you can get undefined behaviour. With namespaces, you can make selections via using namespace that only apply within the active namespace, or do so via a namespace alias so they only apply where that alias is used, but they're actually resolved to distinct linker symbols so can be combined without undefined behaviour. This can be used in a way similar to template policies, but the affect is more implicit, automatic and pervasive - a very powerful language feature.





          UPDATE: addressing marcv81's comment...




          Why not use an interface with two implementations?




          "interface + implementations" is conceptually what choosing a namespace to alias above is doing, but if you mean specifically runtime polymorphism and virtual dispatch:




          • the resultant library or executable doesn't need to contain all implementations and constantly direct calls to the selected one at runtime


          • as one implementation's incorporated the compiler can use myriad optimisations including inlining, dead code elimination, and constants differing between the "implementations" can be used for e.g. sizes of arrays - allowing automatic memory allocation instead of slower dynamic allocation


          • different namespaces have to support the same semantics of usage, but aren't bound to support the exact same set of function signatures as is the case for virtual dispatch


          • with namespaces you can supply custom non-member functions and templates: that's impossible with virtual dispatch (and non-member functions help with symmetric operator overloading - e.g. supporting 22 + my_type as well as my_type + 22)


          • different namespaces can specify different types to be used for certain purposes (e.g. a hash function might return a 32 bit value in one namespace, but a 64 bit value in another), but a virtual interface needs to have unifying static types, which means clumsy and high-overhead indirection like boost::any or boost::variant or a worst case selection where high-order bits are sometimes meaningless


          • virtual dispatch often involves compromises between fat interfaces and clumsy error handling: with namespaces there's the option to simply not provide functionality in namespaces where it makes no sense, giving a compile-time enforcement of necessary client porting effort







          share|improve this answer





















          • 2





            I do not have nearly as much experience as you in C++, but that sounds fairly evil to me. Why not use an interface with two implementations? I can't see any advantage of doing it with namespaces. Please excuse the possible naivety of this comment :)

            – marcv81
            Jul 7 '15 at 3:07











          • @marcv81: some explanation above... questions/thoughts always welcome. Cheers.

            – Tony Delroy
            Jul 7 '15 at 3:59













          • Mindblowing, +1. I understand the speed/size optimisations. For the improved flexibility are you saying we could use for instance C++11 "auto foo = bar()" where bar() has a different return type depending on the used namespace? As much as I understand it I'm not sure I'd try it at work :) One downside I can see is unit testing: I'd rather not link more than 1 executable to run my tests but I agree it's not a blocker for everybody. That's the same reason I prefer to avoid #ifdefs by the way.

            – marcv81
            Jul 7 '15 at 6:38






          • 1





            @marcv81: yes to auto foo = bar();. It can complicate testing, but you can do things like void test1() { using ns1; TEST_EQ(x, y()); } - ditto for test2/ns2 - and run both in one executable. Sometimes using a macro to generate similar test functions with differing using nsN; would simplify things, but writing long macros gets ugly. Moving the test (specifically the function body) into a support file that's multiply included is another option. (Such testing's often impossible for #ifdefed code where the same symbol or function takes on different definitions).

            – Tony Delroy
            Jul 7 '15 at 7:01





















          5














          It can help you for a better comprehension.



          eg:



          std::func <- all function/class from C++ standard library
          lib1::func <- all function/class from specific library
          module1::func <-- all function/class for a module of your system


          You can also think of it as module in your system.



          It can also be usefull for an writing documentation (eg: you can easily document namespace entity in doxygen)






          share|improve this answer

































            2















            1. Aren't name collisions enough of a reason? ADL subtleties, especially with operator overloads, are another.


            2. That's the easiest way. You can also prefix names with the namespace, e.g. my_namespace::name, when defining.







            share|improve this answer































              2














              You can think of namespaces as logical separated units for your application, and logical here means that suppose we have two different classes, putting these two classes each in a file, but when you notice that these classes share something enough to be categorized under one category, that's one strong reason to use namespaces.






              share|improve this answer































                1















                1. Answer: If you ever want to overload the new, placement new, or delete functions you're going to want to do them in a namespace. No one wants to be forced to use your version of new if they don't require the things you require.

                2. Yes






                share|improve this answer























                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4211827%2fwhy-and-how-should-i-use-namespaces-in-c%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  6 Answers
                  6






                  active

                  oldest

                  votes








                  6 Answers
                  6






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  12














                  Here is a good reason (apart from the obvious stated by you).



                  Since namespace can be discontiguous and spread across translation units, they can also be used to separate interface from implementation details.



                  Definitions of names in a namespace can be provided either in the same namespace or in any of the enclosing namespaces (with fully qualified names).






                  share|improve this answer


























                  • Link seems dead or down.

                    – Alex
                    Jan 16 at 9:33











                  • The link seems to work for me.

                    – Giselle Serate
                    Jan 30 at 5:39
















                  12














                  Here is a good reason (apart from the obvious stated by you).



                  Since namespace can be discontiguous and spread across translation units, they can also be used to separate interface from implementation details.



                  Definitions of names in a namespace can be provided either in the same namespace or in any of the enclosing namespaces (with fully qualified names).






                  share|improve this answer


























                  • Link seems dead or down.

                    – Alex
                    Jan 16 at 9:33











                  • The link seems to work for me.

                    – Giselle Serate
                    Jan 30 at 5:39














                  12












                  12








                  12







                  Here is a good reason (apart from the obvious stated by you).



                  Since namespace can be discontiguous and spread across translation units, they can also be used to separate interface from implementation details.



                  Definitions of names in a namespace can be provided either in the same namespace or in any of the enclosing namespaces (with fully qualified names).






                  share|improve this answer















                  Here is a good reason (apart from the obvious stated by you).



                  Since namespace can be discontiguous and spread across translation units, they can also be used to separate interface from implementation details.



                  Definitions of names in a namespace can be provided either in the same namespace or in any of the enclosing namespaces (with fully qualified names).







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Feb 28 '13 at 15:42









                  jogojapan

                  53.8k875111




                  53.8k875111










                  answered Nov 18 '10 at 5:04









                  ChubsdadChubsdad

                  19.2k44992




                  19.2k44992













                  • Link seems dead or down.

                    – Alex
                    Jan 16 at 9:33











                  • The link seems to work for me.

                    – Giselle Serate
                    Jan 30 at 5:39



















                  • Link seems dead or down.

                    – Alex
                    Jan 16 at 9:33











                  • The link seems to work for me.

                    – Giselle Serate
                    Jan 30 at 5:39

















                  Link seems dead or down.

                  – Alex
                  Jan 16 at 9:33





                  Link seems dead or down.

                  – Alex
                  Jan 16 at 9:33













                  The link seems to work for me.

                  – Giselle Serate
                  Jan 30 at 5:39





                  The link seems to work for me.

                  – Giselle Serate
                  Jan 30 at 5:39













                  23














                  One reason that's often overlooked is that simply by changing a single line of code to select one namespaces over another you can select an alternative set of functions/variables/types/constants - such as another version of a protocol, or single-threaded versus multi-threaded support, OS support for platform X or Y - compile and run. The same kind of effect might be achieved by including a header with different declarations, or with #defines and #ifdefs, but that crudely affects the entire translation unit and if linking different versions you can get undefined behaviour. With namespaces, you can make selections via using namespace that only apply within the active namespace, or do so via a namespace alias so they only apply where that alias is used, but they're actually resolved to distinct linker symbols so can be combined without undefined behaviour. This can be used in a way similar to template policies, but the affect is more implicit, automatic and pervasive - a very powerful language feature.





                  UPDATE: addressing marcv81's comment...




                  Why not use an interface with two implementations?




                  "interface + implementations" is conceptually what choosing a namespace to alias above is doing, but if you mean specifically runtime polymorphism and virtual dispatch:




                  • the resultant library or executable doesn't need to contain all implementations and constantly direct calls to the selected one at runtime


                  • as one implementation's incorporated the compiler can use myriad optimisations including inlining, dead code elimination, and constants differing between the "implementations" can be used for e.g. sizes of arrays - allowing automatic memory allocation instead of slower dynamic allocation


                  • different namespaces have to support the same semantics of usage, but aren't bound to support the exact same set of function signatures as is the case for virtual dispatch


                  • with namespaces you can supply custom non-member functions and templates: that's impossible with virtual dispatch (and non-member functions help with symmetric operator overloading - e.g. supporting 22 + my_type as well as my_type + 22)


                  • different namespaces can specify different types to be used for certain purposes (e.g. a hash function might return a 32 bit value in one namespace, but a 64 bit value in another), but a virtual interface needs to have unifying static types, which means clumsy and high-overhead indirection like boost::any or boost::variant or a worst case selection where high-order bits are sometimes meaningless


                  • virtual dispatch often involves compromises between fat interfaces and clumsy error handling: with namespaces there's the option to simply not provide functionality in namespaces where it makes no sense, giving a compile-time enforcement of necessary client porting effort







                  share|improve this answer





















                  • 2





                    I do not have nearly as much experience as you in C++, but that sounds fairly evil to me. Why not use an interface with two implementations? I can't see any advantage of doing it with namespaces. Please excuse the possible naivety of this comment :)

                    – marcv81
                    Jul 7 '15 at 3:07











                  • @marcv81: some explanation above... questions/thoughts always welcome. Cheers.

                    – Tony Delroy
                    Jul 7 '15 at 3:59













                  • Mindblowing, +1. I understand the speed/size optimisations. For the improved flexibility are you saying we could use for instance C++11 "auto foo = bar()" where bar() has a different return type depending on the used namespace? As much as I understand it I'm not sure I'd try it at work :) One downside I can see is unit testing: I'd rather not link more than 1 executable to run my tests but I agree it's not a blocker for everybody. That's the same reason I prefer to avoid #ifdefs by the way.

                    – marcv81
                    Jul 7 '15 at 6:38






                  • 1





                    @marcv81: yes to auto foo = bar();. It can complicate testing, but you can do things like void test1() { using ns1; TEST_EQ(x, y()); } - ditto for test2/ns2 - and run both in one executable. Sometimes using a macro to generate similar test functions with differing using nsN; would simplify things, but writing long macros gets ugly. Moving the test (specifically the function body) into a support file that's multiply included is another option. (Such testing's often impossible for #ifdefed code where the same symbol or function takes on different definitions).

                    – Tony Delroy
                    Jul 7 '15 at 7:01


















                  23














                  One reason that's often overlooked is that simply by changing a single line of code to select one namespaces over another you can select an alternative set of functions/variables/types/constants - such as another version of a protocol, or single-threaded versus multi-threaded support, OS support for platform X or Y - compile and run. The same kind of effect might be achieved by including a header with different declarations, or with #defines and #ifdefs, but that crudely affects the entire translation unit and if linking different versions you can get undefined behaviour. With namespaces, you can make selections via using namespace that only apply within the active namespace, or do so via a namespace alias so they only apply where that alias is used, but they're actually resolved to distinct linker symbols so can be combined without undefined behaviour. This can be used in a way similar to template policies, but the affect is more implicit, automatic and pervasive - a very powerful language feature.





                  UPDATE: addressing marcv81's comment...




                  Why not use an interface with two implementations?




                  "interface + implementations" is conceptually what choosing a namespace to alias above is doing, but if you mean specifically runtime polymorphism and virtual dispatch:




                  • the resultant library or executable doesn't need to contain all implementations and constantly direct calls to the selected one at runtime


                  • as one implementation's incorporated the compiler can use myriad optimisations including inlining, dead code elimination, and constants differing between the "implementations" can be used for e.g. sizes of arrays - allowing automatic memory allocation instead of slower dynamic allocation


                  • different namespaces have to support the same semantics of usage, but aren't bound to support the exact same set of function signatures as is the case for virtual dispatch


                  • with namespaces you can supply custom non-member functions and templates: that's impossible with virtual dispatch (and non-member functions help with symmetric operator overloading - e.g. supporting 22 + my_type as well as my_type + 22)


                  • different namespaces can specify different types to be used for certain purposes (e.g. a hash function might return a 32 bit value in one namespace, but a 64 bit value in another), but a virtual interface needs to have unifying static types, which means clumsy and high-overhead indirection like boost::any or boost::variant or a worst case selection where high-order bits are sometimes meaningless


                  • virtual dispatch often involves compromises between fat interfaces and clumsy error handling: with namespaces there's the option to simply not provide functionality in namespaces where it makes no sense, giving a compile-time enforcement of necessary client porting effort







                  share|improve this answer





















                  • 2





                    I do not have nearly as much experience as you in C++, but that sounds fairly evil to me. Why not use an interface with two implementations? I can't see any advantage of doing it with namespaces. Please excuse the possible naivety of this comment :)

                    – marcv81
                    Jul 7 '15 at 3:07











                  • @marcv81: some explanation above... questions/thoughts always welcome. Cheers.

                    – Tony Delroy
                    Jul 7 '15 at 3:59













                  • Mindblowing, +1. I understand the speed/size optimisations. For the improved flexibility are you saying we could use for instance C++11 "auto foo = bar()" where bar() has a different return type depending on the used namespace? As much as I understand it I'm not sure I'd try it at work :) One downside I can see is unit testing: I'd rather not link more than 1 executable to run my tests but I agree it's not a blocker for everybody. That's the same reason I prefer to avoid #ifdefs by the way.

                    – marcv81
                    Jul 7 '15 at 6:38






                  • 1





                    @marcv81: yes to auto foo = bar();. It can complicate testing, but you can do things like void test1() { using ns1; TEST_EQ(x, y()); } - ditto for test2/ns2 - and run both in one executable. Sometimes using a macro to generate similar test functions with differing using nsN; would simplify things, but writing long macros gets ugly. Moving the test (specifically the function body) into a support file that's multiply included is another option. (Such testing's often impossible for #ifdefed code where the same symbol or function takes on different definitions).

                    – Tony Delroy
                    Jul 7 '15 at 7:01
















                  23












                  23








                  23







                  One reason that's often overlooked is that simply by changing a single line of code to select one namespaces over another you can select an alternative set of functions/variables/types/constants - such as another version of a protocol, or single-threaded versus multi-threaded support, OS support for platform X or Y - compile and run. The same kind of effect might be achieved by including a header with different declarations, or with #defines and #ifdefs, but that crudely affects the entire translation unit and if linking different versions you can get undefined behaviour. With namespaces, you can make selections via using namespace that only apply within the active namespace, or do so via a namespace alias so they only apply where that alias is used, but they're actually resolved to distinct linker symbols so can be combined without undefined behaviour. This can be used in a way similar to template policies, but the affect is more implicit, automatic and pervasive - a very powerful language feature.





                  UPDATE: addressing marcv81's comment...




                  Why not use an interface with two implementations?




                  "interface + implementations" is conceptually what choosing a namespace to alias above is doing, but if you mean specifically runtime polymorphism and virtual dispatch:




                  • the resultant library or executable doesn't need to contain all implementations and constantly direct calls to the selected one at runtime


                  • as one implementation's incorporated the compiler can use myriad optimisations including inlining, dead code elimination, and constants differing between the "implementations" can be used for e.g. sizes of arrays - allowing automatic memory allocation instead of slower dynamic allocation


                  • different namespaces have to support the same semantics of usage, but aren't bound to support the exact same set of function signatures as is the case for virtual dispatch


                  • with namespaces you can supply custom non-member functions and templates: that's impossible with virtual dispatch (and non-member functions help with symmetric operator overloading - e.g. supporting 22 + my_type as well as my_type + 22)


                  • different namespaces can specify different types to be used for certain purposes (e.g. a hash function might return a 32 bit value in one namespace, but a 64 bit value in another), but a virtual interface needs to have unifying static types, which means clumsy and high-overhead indirection like boost::any or boost::variant or a worst case selection where high-order bits are sometimes meaningless


                  • virtual dispatch often involves compromises between fat interfaces and clumsy error handling: with namespaces there's the option to simply not provide functionality in namespaces where it makes no sense, giving a compile-time enforcement of necessary client porting effort







                  share|improve this answer















                  One reason that's often overlooked is that simply by changing a single line of code to select one namespaces over another you can select an alternative set of functions/variables/types/constants - such as another version of a protocol, or single-threaded versus multi-threaded support, OS support for platform X or Y - compile and run. The same kind of effect might be achieved by including a header with different declarations, or with #defines and #ifdefs, but that crudely affects the entire translation unit and if linking different versions you can get undefined behaviour. With namespaces, you can make selections via using namespace that only apply within the active namespace, or do so via a namespace alias so they only apply where that alias is used, but they're actually resolved to distinct linker symbols so can be combined without undefined behaviour. This can be used in a way similar to template policies, but the affect is more implicit, automatic and pervasive - a very powerful language feature.





                  UPDATE: addressing marcv81's comment...




                  Why not use an interface with two implementations?




                  "interface + implementations" is conceptually what choosing a namespace to alias above is doing, but if you mean specifically runtime polymorphism and virtual dispatch:




                  • the resultant library or executable doesn't need to contain all implementations and constantly direct calls to the selected one at runtime


                  • as one implementation's incorporated the compiler can use myriad optimisations including inlining, dead code elimination, and constants differing between the "implementations" can be used for e.g. sizes of arrays - allowing automatic memory allocation instead of slower dynamic allocation


                  • different namespaces have to support the same semantics of usage, but aren't bound to support the exact same set of function signatures as is the case for virtual dispatch


                  • with namespaces you can supply custom non-member functions and templates: that's impossible with virtual dispatch (and non-member functions help with symmetric operator overloading - e.g. supporting 22 + my_type as well as my_type + 22)


                  • different namespaces can specify different types to be used for certain purposes (e.g. a hash function might return a 32 bit value in one namespace, but a 64 bit value in another), but a virtual interface needs to have unifying static types, which means clumsy and high-overhead indirection like boost::any or boost::variant or a worst case selection where high-order bits are sometimes meaningless


                  • virtual dispatch often involves compromises between fat interfaces and clumsy error handling: with namespaces there's the option to simply not provide functionality in namespaces where it makes no sense, giving a compile-time enforcement of necessary client porting effort








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 7 '15 at 3:59

























                  answered Nov 18 '10 at 6:57









                  Tony DelroyTony Delroy

                  84k10129190




                  84k10129190








                  • 2





                    I do not have nearly as much experience as you in C++, but that sounds fairly evil to me. Why not use an interface with two implementations? I can't see any advantage of doing it with namespaces. Please excuse the possible naivety of this comment :)

                    – marcv81
                    Jul 7 '15 at 3:07











                  • @marcv81: some explanation above... questions/thoughts always welcome. Cheers.

                    – Tony Delroy
                    Jul 7 '15 at 3:59













                  • Mindblowing, +1. I understand the speed/size optimisations. For the improved flexibility are you saying we could use for instance C++11 "auto foo = bar()" where bar() has a different return type depending on the used namespace? As much as I understand it I'm not sure I'd try it at work :) One downside I can see is unit testing: I'd rather not link more than 1 executable to run my tests but I agree it's not a blocker for everybody. That's the same reason I prefer to avoid #ifdefs by the way.

                    – marcv81
                    Jul 7 '15 at 6:38






                  • 1





                    @marcv81: yes to auto foo = bar();. It can complicate testing, but you can do things like void test1() { using ns1; TEST_EQ(x, y()); } - ditto for test2/ns2 - and run both in one executable. Sometimes using a macro to generate similar test functions with differing using nsN; would simplify things, but writing long macros gets ugly. Moving the test (specifically the function body) into a support file that's multiply included is another option. (Such testing's often impossible for #ifdefed code where the same symbol or function takes on different definitions).

                    – Tony Delroy
                    Jul 7 '15 at 7:01
















                  • 2





                    I do not have nearly as much experience as you in C++, but that sounds fairly evil to me. Why not use an interface with two implementations? I can't see any advantage of doing it with namespaces. Please excuse the possible naivety of this comment :)

                    – marcv81
                    Jul 7 '15 at 3:07











                  • @marcv81: some explanation above... questions/thoughts always welcome. Cheers.

                    – Tony Delroy
                    Jul 7 '15 at 3:59













                  • Mindblowing, +1. I understand the speed/size optimisations. For the improved flexibility are you saying we could use for instance C++11 "auto foo = bar()" where bar() has a different return type depending on the used namespace? As much as I understand it I'm not sure I'd try it at work :) One downside I can see is unit testing: I'd rather not link more than 1 executable to run my tests but I agree it's not a blocker for everybody. That's the same reason I prefer to avoid #ifdefs by the way.

                    – marcv81
                    Jul 7 '15 at 6:38






                  • 1





                    @marcv81: yes to auto foo = bar();. It can complicate testing, but you can do things like void test1() { using ns1; TEST_EQ(x, y()); } - ditto for test2/ns2 - and run both in one executable. Sometimes using a macro to generate similar test functions with differing using nsN; would simplify things, but writing long macros gets ugly. Moving the test (specifically the function body) into a support file that's multiply included is another option. (Such testing's often impossible for #ifdefed code where the same symbol or function takes on different definitions).

                    – Tony Delroy
                    Jul 7 '15 at 7:01










                  2




                  2





                  I do not have nearly as much experience as you in C++, but that sounds fairly evil to me. Why not use an interface with two implementations? I can't see any advantage of doing it with namespaces. Please excuse the possible naivety of this comment :)

                  – marcv81
                  Jul 7 '15 at 3:07





                  I do not have nearly as much experience as you in C++, but that sounds fairly evil to me. Why not use an interface with two implementations? I can't see any advantage of doing it with namespaces. Please excuse the possible naivety of this comment :)

                  – marcv81
                  Jul 7 '15 at 3:07













                  @marcv81: some explanation above... questions/thoughts always welcome. Cheers.

                  – Tony Delroy
                  Jul 7 '15 at 3:59







                  @marcv81: some explanation above... questions/thoughts always welcome. Cheers.

                  – Tony Delroy
                  Jul 7 '15 at 3:59















                  Mindblowing, +1. I understand the speed/size optimisations. For the improved flexibility are you saying we could use for instance C++11 "auto foo = bar()" where bar() has a different return type depending on the used namespace? As much as I understand it I'm not sure I'd try it at work :) One downside I can see is unit testing: I'd rather not link more than 1 executable to run my tests but I agree it's not a blocker for everybody. That's the same reason I prefer to avoid #ifdefs by the way.

                  – marcv81
                  Jul 7 '15 at 6:38





                  Mindblowing, +1. I understand the speed/size optimisations. For the improved flexibility are you saying we could use for instance C++11 "auto foo = bar()" where bar() has a different return type depending on the used namespace? As much as I understand it I'm not sure I'd try it at work :) One downside I can see is unit testing: I'd rather not link more than 1 executable to run my tests but I agree it's not a blocker for everybody. That's the same reason I prefer to avoid #ifdefs by the way.

                  – marcv81
                  Jul 7 '15 at 6:38




                  1




                  1





                  @marcv81: yes to auto foo = bar();. It can complicate testing, but you can do things like void test1() { using ns1; TEST_EQ(x, y()); } - ditto for test2/ns2 - and run both in one executable. Sometimes using a macro to generate similar test functions with differing using nsN; would simplify things, but writing long macros gets ugly. Moving the test (specifically the function body) into a support file that's multiply included is another option. (Such testing's often impossible for #ifdefed code where the same symbol or function takes on different definitions).

                  – Tony Delroy
                  Jul 7 '15 at 7:01







                  @marcv81: yes to auto foo = bar();. It can complicate testing, but you can do things like void test1() { using ns1; TEST_EQ(x, y()); } - ditto for test2/ns2 - and run both in one executable. Sometimes using a macro to generate similar test functions with differing using nsN; would simplify things, but writing long macros gets ugly. Moving the test (specifically the function body) into a support file that's multiply included is another option. (Such testing's often impossible for #ifdefed code where the same symbol or function takes on different definitions).

                  – Tony Delroy
                  Jul 7 '15 at 7:01













                  5














                  It can help you for a better comprehension.



                  eg:



                  std::func <- all function/class from C++ standard library
                  lib1::func <- all function/class from specific library
                  module1::func <-- all function/class for a module of your system


                  You can also think of it as module in your system.



                  It can also be usefull for an writing documentation (eg: you can easily document namespace entity in doxygen)






                  share|improve this answer






























                    5














                    It can help you for a better comprehension.



                    eg:



                    std::func <- all function/class from C++ standard library
                    lib1::func <- all function/class from specific library
                    module1::func <-- all function/class for a module of your system


                    You can also think of it as module in your system.



                    It can also be usefull for an writing documentation (eg: you can easily document namespace entity in doxygen)






                    share|improve this answer




























                      5












                      5








                      5







                      It can help you for a better comprehension.



                      eg:



                      std::func <- all function/class from C++ standard library
                      lib1::func <- all function/class from specific library
                      module1::func <-- all function/class for a module of your system


                      You can also think of it as module in your system.



                      It can also be usefull for an writing documentation (eg: you can easily document namespace entity in doxygen)






                      share|improve this answer















                      It can help you for a better comprehension.



                      eg:



                      std::func <- all function/class from C++ standard library
                      lib1::func <- all function/class from specific library
                      module1::func <-- all function/class for a module of your system


                      You can also think of it as module in your system.



                      It can also be usefull for an writing documentation (eg: you can easily document namespace entity in doxygen)







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 18 '10 at 6:55

























                      answered Nov 18 '10 at 5:09









                      PhongPhong

                      4,70722653




                      4,70722653























                          2















                          1. Aren't name collisions enough of a reason? ADL subtleties, especially with operator overloads, are another.


                          2. That's the easiest way. You can also prefix names with the namespace, e.g. my_namespace::name, when defining.







                          share|improve this answer




























                            2















                            1. Aren't name collisions enough of a reason? ADL subtleties, especially with operator overloads, are another.


                            2. That's the easiest way. You can also prefix names with the namespace, e.g. my_namespace::name, when defining.







                            share|improve this answer


























                              2












                              2








                              2








                              1. Aren't name collisions enough of a reason? ADL subtleties, especially with operator overloads, are another.


                              2. That's the easiest way. You can also prefix names with the namespace, e.g. my_namespace::name, when defining.







                              share|improve this answer














                              1. Aren't name collisions enough of a reason? ADL subtleties, especially with operator overloads, are another.


                              2. That's the easiest way. You can also prefix names with the namespace, e.g. my_namespace::name, when defining.








                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 18 '10 at 5:06









                              Fred NurkFred Nurk

                              11.7k32957




                              11.7k32957























                                  2














                                  You can think of namespaces as logical separated units for your application, and logical here means that suppose we have two different classes, putting these two classes each in a file, but when you notice that these classes share something enough to be categorized under one category, that's one strong reason to use namespaces.






                                  share|improve this answer




























                                    2














                                    You can think of namespaces as logical separated units for your application, and logical here means that suppose we have two different classes, putting these two classes each in a file, but when you notice that these classes share something enough to be categorized under one category, that's one strong reason to use namespaces.






                                    share|improve this answer


























                                      2












                                      2








                                      2







                                      You can think of namespaces as logical separated units for your application, and logical here means that suppose we have two different classes, putting these two classes each in a file, but when you notice that these classes share something enough to be categorized under one category, that's one strong reason to use namespaces.






                                      share|improve this answer













                                      You can think of namespaces as logical separated units for your application, and logical here means that suppose we have two different classes, putting these two classes each in a file, but when you notice that these classes share something enough to be categorized under one category, that's one strong reason to use namespaces.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 18 '10 at 5:08









                                      Kenan DKenan D

                                      4,4892751




                                      4,4892751























                                          1















                                          1. Answer: If you ever want to overload the new, placement new, or delete functions you're going to want to do them in a namespace. No one wants to be forced to use your version of new if they don't require the things you require.

                                          2. Yes






                                          share|improve this answer




























                                            1















                                            1. Answer: If you ever want to overload the new, placement new, or delete functions you're going to want to do them in a namespace. No one wants to be forced to use your version of new if they don't require the things you require.

                                            2. Yes






                                            share|improve this answer


























                                              1












                                              1








                                              1








                                              1. Answer: If you ever want to overload the new, placement new, or delete functions you're going to want to do them in a namespace. No one wants to be forced to use your version of new if they don't require the things you require.

                                              2. Yes






                                              share|improve this answer














                                              1. Answer: If you ever want to overload the new, placement new, or delete functions you're going to want to do them in a namespace. No one wants to be forced to use your version of new if they don't require the things you require.

                                              2. Yes







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Nov 18 '10 at 5:07









                                              wheatieswheaties

                                              30.1k1072121




                                              30.1k1072121






























                                                  draft saved

                                                  draft discarded




















































                                                  Thanks for contributing an answer to Stack Overflow!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid



                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function () {
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4211827%2fwhy-and-how-should-i-use-namespaces-in-c%23new-answer', 'question_page');
                                                  }
                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  MongoDB - Not Authorized To Execute Command

                                                  in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                                                  How to fix TextFormField cause rebuild widget in Flutter