简体   繁体   中英

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:

  • A collection of string functions
  • A collection of math functions

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.

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 .

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM