THND
THND

Reputation: 217

How to limit the scope of a "using namespace ..."? c++

I have file with "my namespace"'s (myns::) methods implementations, there are lots of "myns::" before functions. I want to write using namespace, but it will be visible in other files. I can't write "static" before "using namespace mysp;".

my_namespace_file.h:

namespace myns {
  void F1();
  void F2();
}

my_imp_file.h:

#include "my_namespace_file.h"

// problem is here
using namespace myns;

void F1() {}
void F2() {}

if I use here "using namespace myns;" and include my_imp_file.h in other files I will do not use in this files "myns::"

Upvotes: 0

Views: 947

Answers (2)

Yksisarvinen
Yksisarvinen

Reputation: 22211

Simple as this:

#include "my_namespace_file.h"

namespace myns {

void A::F1() {} // class name must be repeated, because you cannot open namespace of the class
void A::F2() {}

}

Since you should never #include file with implementations, you can use using namespace myns; as well, but that may backfire if you will ever create another class A in a different namespace. Better to just use namespace correctly.

Upvotes: 2

Eisverygoodletter
Eisverygoodletter

Reputation: 173

niceheadername.h:

namespace myns{
  extern void coolFunctionName(); // I exist!
}

nicecppfilename.cpp:

#include "niceheadername.h" // I exist in "niceheadername.h"
void myns::coolFunctionName(){ // this is what I contain!
  //put content here
}

then, in all other files that you write #include "niceheadername.h" to tell the compiler where to find those functions.

Upvotes: 1

Related Questions