Jump to content
  • Advertisement
Sign in to follow this  
toddhd

Unity Ok, using namespace or not? And why?

This topic is 4984 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By Aryndon
      Project Redemption is an semi-fantasy RPG with a linear story and an elaborate combat system.
      We are building in Unity and are currently looking animators and artists.
      What we are looking for
      -Someone who is okay with split revenue/profits when finished
      -Collaborate with others in the team. Do you have an idea/thought on what should be included? Tell us!
      -Someone who wants to work with people that are passionate about this project
      If you are interested. Please message me and I will get back to you as soon as possible! Or add me on Discord AJ#6664
    • By Aggrojag
      Hello!
      I'm working on a game that is a narrative driven dark comedy with some small aspects of platforming and puzzle solving. The project is rather small as well. It touches on topics such as suicide, mental illness, family, corruption, free-will, and redemption.
      This project is exercise in polish, this means some experimentation will be needed along with some reworking of assets as they're provided.
      This will be a revshare model.
      First, I'm looking for a 2D sprite artist, not pixelated, that can compliment the style of the attached images, and be similar to the temporary character.
      We are looking to bring on a SFX designer at this time. Full list of required SFX will be available upon request, as well as a build with all elements related to sound implemented in some form (many SFXs pulled from the web for now). Will likely require some field recording, and some pretty strange SFX for when things get weird. I imagine a good portion of these will be quite fun to create.
      Lastly, I'm looking for a male voice actor, English should be your primary language. There will be at minimum two characters that will need to be brought to life through vocals. The first voice is similar to Marvin from Hitchhiker's Guide to the Galaxy. A reference for the second voice would be a mix of Ren (Ren & Stimpy), and Android 21 (DragonBallFighterZ). Due to formatting, I'm not including YouTube links in the post, sorry.
       
      WIP Scene with our custom shaders attached (platforms are lazily placed, as this was an asset test):

      A scene with dynamic lighting and temp character:

       
      Unshaded asset:

      If you made it to the bottom, thank you, and I look forward to hearing from you.
    • By SickTwistGames
      Ok, firstly, Hi.
       
      This is my first post on this forum. I am an Indie Dev making my first game so bear with me when I say dumb stuff, I'm on a huge learning curve.
       
      My first question is about inventory systems for unity. I am trying to make a survival type game with crafting. I have purchased Inventory manager pro by devdog from the unity asset store and it seems like a pretty powerful assett but for an intermediate coder its a little tough to use.  I'm beginning to wonder if it was the right purchase.
      So my question is.... does anyone have any experience of inventory plugins / systems for unity and can anyone reccomend a system to me?
      It needs to have the following: Loot system, crafting system, character sheet, blueprint system,  character stats system. Ideally with as little coding as possible.
       
      Thanks
    • By ethancodes
      I've got a bug with my brick breaker style game. The bricks move down one line at a time ever 1.5 seconds. What appears to be happening is occasionally the ball will be just about to hit the brick when the brick moves down a line, and now the ball is behind it. I'm not sure how to fix this. I have two ideas but I'm not sure of implementation. 1 solution would be to check where they were and where they are going to be before rendering the frame. Then if they crossed paths, then register the brick as hit. Solution 2 would be change how the bricks move. I could maybe slide them down line by line, instead of a jump down. I'm not sure of this will fix the issue or not. Any ideas?
    • By Pixeye
      I wrote an extension for unity inspector that allows to group/fold variables. 
      Available on github  , cheers!

       
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!