Trevor Hickey
Trevor Hickey

Reputation: 37806

Scoping with pre-made namespace (C++)

To avoid scoping everything from the STL, you can type

using namespace std;

To avoid scoping only a few things, you can type:

using std::cout;  
using std::cin;

I want to write a library that acts the same way. However, instead of being able to include specific classes, I want to be able to include specific collections of functions.

So, for example, I code:

They are part of the same namespace, but I can include the chunks I want


This is sudo-ish code, but I think it gets my idea across:

namespace Everything{
    namespace StringFunctions{
        void str1(string & str);
        void str2(string & str);
        void str3(string & str);
        void str4(string & str);
        void str5(string & str);
    }

    namespace MathFunctions {
        void math1(int & num);
        void math2(int & num);
        void math3(int & num);
        void math4(int & num);
        void math5(int & num);
    }
}

then I want to be able to do something like:

#include "Everything.h"
using Everything::Stringfunctions;

int main(){

    str1("string"); //this works, I can call this!
    math1(111);     //compile error: I've never heard of that function!

    return 0;
}

Obviously this does not work, and I am kind of confused on how to divide up my library. I don't want to make them classes and then have to use the "dot operator" everywhere, but I also don't want to include a ton of header files.

Maybe I am going about this the wrong way. I hope everyone can help me take the right approach here.


EDIT:

It works by writing:

using namespace Everything::Stringfunctions;

This is very obvious now in hindsight.

Upvotes: 4

Views: 169

Answers (3)

dreamlax
dreamlax

Reputation: 95315

What you want seems to work, provided you use using namespace rather than just using. See here (program compiles and outputs '5').

Upvotes: 0

Mark B
Mark B

Reputation: 96233

You should consider splitting functionality into different headers regardless, otherwise you'll wind up with nightmare compilation times. That said I think using namespace Everything::Stringfunctions; ought to do it (with the extra namespace in there. I didn't try compiling though).

Upvotes: 0

Mankarse
Mankarse

Reputation: 40613

The way that you have written your library in the example that you gave is sufficient.

People can get every function from the namespace Everything::Stringfunctions by using the directive using namespace Everything::Stringfunctions.

Upvotes: 3

Related Questions