Sign in to follow this  
toddhd

Unity Ok, using namespace or not? And why?

Recommended Posts

Twice today I have seen posts in various places where people have said: ...Don't put using namespace std; in your headers, use std::string (or whatever) instead... Here and In a comment here I thought the whole point of using namespaces to begin with was to avoid having to use the longer notation? In my other posts about my IniFile class, several people suggested that I make it a namespace instead of class for the exact reason of being able to use "using namespace". So which is it? To use namespace or not to use namespace? That is my question :)

Share this post


Link to post
Share on other sites
Everyone has different coding styles. People who say, "Don't type 'using namespace...'", should realize that everyone has different coding styles. I would have to agree with them, however, that it is better practice when you don't mind typing more. This way you know what is actually local to the file, and what you need to access throught a specific scope using '::'.

My opinion is if you only need to type 'namespace::function()', then type it out, otherwise I would put a using to avoid typing so much.

As far as string goes, I've had some problems when including specific headers in VC6, so I usually just type out the std::string

Share this post


Link to post
Share on other sites
You can put using namespace std in your own cpp file if you must.

When things are declared in a namespace, the intention is to avoid polluting the global namespace with names. For example if I write a class called string and you write a class called string and I want to use your library with my library, I've got a problem. If both headers declaring the classes are included the compiler can't tell the difference between the two when I refer to a string (and neither can I). So if we both put our string classes nicely into a namespace they can be qualified with the namespace:


#ifndef TODDLIB_STRING_H
#define TODDLIB_STRING_H

namespace toddlib {
class string;//etc
}

#endif




#ifndef PETELIB_STRING_H
#define PETELIB_STRING_H

namespace petelib {
class string;//etc
}

#endif




#include "toddlib/string.h"
#include "petelib/string.h"

int main() {
using petelib::string
string address;//uses petelib::string no ambiguity

toddlib::string name;//uses toddlib::string no ambiguity
return 0;
}




So they coexist nicely. However, if you have some header which says using toddlib::string (or even worse using namespace toddlib), then any place I include your header, I won't be able to unambiguously use my own string:


#ifndef TODDLIB_SOMETHING_BAD_H
#define TODDLIB_SOMETHING_BAD_H

#include "string"
using namespace toddlib;

void printName(string);//uses string from toddlib
//void printName(toddlib::string);//better way doesn't need 'using'

#endif



#include "toddlib/something_bad.h"
#include "petelib/string"

int main() {
using petelib::string
string address;//ambiguity because something_bad.h brought
//toddlib::string into global scope
return 0;
}

Share this post


Link to post
Share on other sites
The whole reason is to avoid conflicts with type names, global variables, etc. If I released a library with a class in it, I'd want to make sure that it wouldn't interfere with the user's code if they happened to have a class with the same name.

Also, you can split your project into different namespaces to help you organise it. For example: namespace Engine, namespace Engine::Foundation, namespace Engine::Core.

Share this post


Link to post
Share on other sites
Quote:
Original post by petewood
However, if you have some header which says using toddlib::string (or even worse using namespace toddlib), then any place I include your header, I won't be able to unambiguously use my own string


Ah... I see what you are saying now. So if I release my IniFile class for someone else to use, and using namespace whatever is in my header, then that namespace will be pulled into their program too, possibly causing problems, or at least adding overhead.

Ok, that makes sense.

Share this post


Link to post
Share on other sites
In regard to the worries related to excessive typing:

You can alias namespaces. So I have namespaces which divide my projects up into separate parts:


namespace library_name {
namespace component_name {
namespace detail {
}
}
}


When I am working on the detail part I wrap the whole cpp file as above and don't have to use all the qualifications (unless there is some ambiguity).

When I am making use of the library component I might alias the library name and component to lncn (library name component name, see (c:)


namespace lncn = library_name::component_name;

lncn::string player;
lncn::string comments;
//or
using lncn;
string player2;
string more_comments;

Share this post


Link to post
Share on other sites
Quote:
Original post by toddhd
Quote:
Original post by petewood
However, if you have some header which says using toddlib::string (or even worse using namespace toddlib), then any place I include your header, I won't be able to unambiguously use my own string

Ah... I see what you are saying now. So if I release my IniFile class for someone else to use, and using namespace whatever is in my header, then that namespace will be pulled into their program too, possibly causing problems, or at least adding overhead.

Ok, that makes sense.


Right, you've got it. (c:

Basically it's to do with being friendly.

There won't be any overhead at runtime, only at compile time with the set of names the compiler will consider for lookup.

Share this post


Link to post
Share on other sites
Quote:
Original post by toddhd
...Don't put using namespace std; in your headers, use std::string (or whatever) instead...

Yes, because it can cause naming conflicts in code that 'uses' those headers.
Quote:
I thought the whole point of using namespaces to begin with was to avoid having to use the longer notation?

To avoid having to write (using SDL as an example) SDL_Init instead of Init. But if your headers start using namespaces, any file that includes them will also be forced to include those namespaces. This becomes problematic when two Init functions exist in seperate namespaces. Why?

1) The programmer is forced, if both namespaces are included, to forevermore use sdl::init and myotherlib::init (if both these existed) even if he only really wanted to call one of those. Thus, by saving some typing in the headers (which have less code (usually) than source files), you can force both more typing in using code (read: source files, the longer ones) and potential headaches (not realising that the headers use a namespace, causing compile errors with the bellow code:)

#include "c++sdl/sdl.hh" //uses namespace sdl like the sneaky devil you made it be
#include "otherlib/otherlib.hh"
using namespace otherlib;

//...

void SomeClass::InitSubsystemA ( void )
{
if (! gOtherLibInitialized) init(); //ERROR: sdl::init or otherlib::init?
}



Quote:
In my other posts about my IniFile class, several people suggested that I make it a namespace instead of class for the exact reason of being able to use "using namespace".


Sounds good, but only do the using namespace bit in your SOURCE FILES, NOT your headers. Using them in headers entirely defeats the purpouse of namespaces for any code that uses those headers.

Quote:
So which is it? To use namespace or not to use namespace?
That is my question :)


Use them or I will be angry ;-).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      627763
    • Total Posts
      2978974
  • Similar Content

    • By KARTHI
      Free software
       
      1. Lumberyard (Game engine) open-source and free tool
      Amazon Lumberyard is a free cross-platform triple-A game engine developed by Amazon and based on the architecture of Cry Engine, which was licensed from Crytek in 2015.
       
      2. Sculptris (sculpture tool) open-source and free tool
      Sculptris is a virtual sculpting software program, with a primary focus on the concept of modeling clay. It entered active development in early December 2009, and the most recent release was in 2011.
       
      3. Make human (game model creator) open-source and free tool
      Make human is an open-source 3D computer graphics software middleware designed for the prototyping of photorealistic humanoids. It is developed by a community of programmers, artists, and academics interested in 3D modeling of characters.
       
      4. Ipi soft (motion capture software) not free tool
      iPi Motion Capture is a scalable markerless motion capture software tool that supports 1 or 2 Kinect cameras or 3 to 6 Sony PlayStation Eye cameras to track a human action and convert it into a motion capture file
       
       5. Blender (Complete tool) for modeling, texturing and so on (open-source and free tool)
       Blender is a professional, free and open-source 3D computer graphics software toolset used for creating animated films, visual effects, art, 3D printed models, interactive 3D applications and video games.
                 
      6. Audacity (music editor) open-source and free tool
      Audacity is a free open source digital audio editor and recording computer software application, available for Windows, OS X, Linux and other operating systems.
                 
      7. Awesome bump (bump map editor) open-source and free tool (optional)
      Awesome Bump is a free program written using Qt library designed to generate normal, height, specular or ambient occlusion textures from a single image.
       
      8. Faceware (facial animation) not free tool
      Faceware Technologies is an American company that designs facial animation and motion capture technology. The company was established under Image Metrics and became its own company at the beginning of 2012.
       
      9. GIMP (image editing) open-source and free tool
      GIMP is a free and open-source raster graphics editor used for image retouching and editing, free-form drawing, converting between different image formats, and more specialized tasks. Through this you can also create bump maps
       
      10. Meshlab (mesh repair) open-source and free tool (Optional)
      MeshLab is an advanced 3D mesh processing software system that is oriented to the management and processing of unstructured large meshes and provides a set of tools for editing, cleaning, healing.
       
      11. LibreOffice (create documents) open-source and free tool
      LibreOffice is a free and open source office suite, a project of The Document Foundation. It was forked from OpenOffice.org in 2010, which was an open-sourced version of the earlier StarOffice.
                 
      12. Atom (coding software) open-source and free tool
      Atom is a free and open-source text and source code editor for macOS, Linux, and Microsoft Windows with support for plug-ins written in Node.js, and embedded Git Control, developed by GitHub.
                 
       
      Useful websites
      free image
                 
      Reference images will be found on Pinterest
       
      Free Sounds
       
      1.      Freesound.org
      2.      99Sounds.org
      3.      NoiseForFun.com
      4.      Incompetech.com
      5.      OpenGameArt.org
      6.      RaisedBeaches.com
      7.      Musopen.org
      8.      PlayonLoop.com
      9.      Bensound.com
      10.   SoundJay.com
      11.   Dig.ccmixter.org
      12.   Soundgator.com
      13.   Pacdv.com
      14.   Freesfx.co.uk
      15.   Soundtrack.imphenzia.com
      16.   Bxfr.net
       
      Download the free music tracks from these websites
       
      1. http://incompetech.com/music/
      2. http://dig.ccmixter.org/
      3. http://www.joshwoodward.com
      4. http://www.youtube.com/audiolibrary
       
      I hope this information will help full to you. I am got so stress to collect this data so don't waste it 
      🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤗🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔
       
       
    • By rXpSwiss
      Hello,
      I am looking for a team to stop developing project alone and start doing bigger things.  I would like a team that is organized and serious even of it is just a hobby. I don't want a project to be dropped every week and the team to disband after 2 months. Even though it is a hobby the quality and complexity of the game should be on par with a game that would be released on a major platform.

      I have experience with UE4, Unity and making my own engine with OpenGL. I prefer UE4 for 3D and Unity for 2D but I am willing to work with both.
      Every one of the games I worked on (personal project) involve multiplayer and netcode, I used what UE4 provided but for unity I used Forge Remastered which gave me a bigger control on how to optimize everything.
      I play several instruments, know about game design and am able to do small modeling task but I am before everything a programmer.
      I play mostly competitive fighting games these days (SFV, MvCi, GG, T7) but before I started getting serious into these types of games it was mostly FPS (CS1.6, UT2k4, Quake 3) and Dota-like. As you can see I love competitive multiplayer games but I play solo games too. I have a preference for darker theme games(F.E.A.R, HL, Shin Megami Tensei/Persona, Last of Us, SH2, RE7) even though I play everything offering me a challenge or some peace (Don't Starve, Stardew Valley, Darkest Dungeon, Zelda etc).
      I do have several ideas for games with a very clear direction gameplay, marketing and art but I am not looking for a team to work on my ideas, I just have them if needed.
      Feel free to ask questions here or PM me if you prefer.
      Best regards,
      rXp
    • By KARTHI
      Please reply me about this
    • By KARTHI
      Currently I using makehuman to make a 3d models but I am not satisfied with that model. If any use this please reply about the quality and details of models. 
      🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔
    • By KARTHI
      I planned to make a space game so I need a knowledge about 3d planet making so anyone help me to make it possible
      🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔
  • Popular Now