Defining a scope with a pre-created namespace (C ++)

To avoid selecting everything from the STL, you can enter

using namespace std; 

To avoid defining just a few things, you can enter:

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

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

So, for example, I have the code:

  • String Functions Collection
  • Set of math functions

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


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

 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'm a little confused about how to split my library. I don’t want to create classes and then use the β€œdot operator” everywhere, but I also don’t want to include a ton of header files.

Maybe I'm wrong about that. 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 retrospect.

+4
source share
3 answers

The way you wrote your library in the example you gave is sufficient.

People can get each function from the Everything::Stringfunctions using namespace Everything::Stringfunctions .

+3
source

You should consider splitting functions into different headers regardless of whether you end up compiling nightmares. However, I think using namespace Everything::Stringfunctions; should do it (with the addition of namespace there. I haven't even tried to compile).

0
source

It seems that you want to work if you are using namespace , not just using . See here (the program compiles and displays "5").

0
source

Source: https://habr.com/ru/post/1386021/


All Articles