Using Multiple Namespaces

Aug 15, 2008 at 6:02pm
I've just tried using two namespaces in a project at the same time, using the "using namespace ... ;" syntax for each namespace. MinGW threw errors claiming variables and functions weren't defined. Is it possible to use two namespaces in this way, without having to resort to the "namespace::member" syntax for one of the namespaces?
Aug 15, 2008 at 6:20pm
Guess what namespaces are designed for...
The "using namespace" directive is *EVIL* and should be illegal alltogether, as far as I am concerned. Most likely you only require single types. If you really feel the urge, use
using namespace::member
for the members you really require to be in global scope.

To your question: it is possible to do so if and only if no ambiguities arise. Otherwise, how should name resolution work?
Aug 15, 2008 at 9:32pm
Good points. Thanks for your help :-).
Aug 15, 2008 at 11:42pm
That doesn't solve the problem. MinGW doesn't throw random errors. If it says something is not defined, then it is very likely not defined, or not defined properly.

The only place that using directives are evil is in header files. Multiple using directives are additive, and only conflict when you try to use the same unqualified name from different namespaces with using.

Make sure you have everything properly defined, #included, and include-guarded.
1
2
3
4
5
6
7
8
9
// foo.h
#ifndef FOO_H
#define FOO_H
namespace foo
  {
  extern const int answer;
  void print_answer();
  }
#endif 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// foo.cpp
#include <iostream>
#include "foo.h"

namespace foo
  {
  using namespace std;

  const int answer = 42;
  void print_answer()
    {
    cout << "The answer is " << answer << endl;
    }

  }

1
2
3
4
5
6
7
8
9
10
11
12
13
// main.cpp
#include <iostream>
#include "foo.h"

using namespace std;
using namespace foo;

int main()
  {
  cout << "Hello world!\n";
  print_answer();
  return 0;
  }
Topic archived. No new replies allowed.