Shorten Name Names

If you use nested namespaces, declarations in header files can be very long and unreadable.

//header1
namespace test { namespace test1 {
class Test {};
} } //namespace

In header2 of the program:

#include "header1"

namespace test2 {

class Test1 {
  void test(test::test1::Test &test) {}
  void test1(test::test1::Test &test) {}
  void test2(test::test1::Test &test1, test::test1::Test &test2) {}
};

}

Is it possible to shorten the names in header2?

+3
source share
5 answers

Here is my favorite technique:

#include "header1"

namespace test2 {

class Test1 {
 private:
  typedef ::test::test1::Test MeaningfulName;

  void test(MeaningfulName &test) {}
  void test1(MeaningfulName &test) {}
  void test2(MeaningfulName &test1, MeaningfulName &test2) {}
};

}

I make my typedef aliases private, but I put them at the beginning of the class declaration. It does not matter that they are private to the rest of the program, because no one will use aliases, they will use the actual type name or their own alias for the name.

, . , , / - . . , .

- <:, , . , , , .

+5

, :

namespace tt=test::test1;
+4

, using, . - , , . using , , . cpp using namespace test1, test1, , , , cpp , .

, , - , cpp, . : " test1 test2, ?"

+1

header2.h

using namespace test::test1;
0

, , , , , Google .

, , #define #undef .

:

#include "header1"

#define shortNS test::test1
namespace test2 {
    class Test1 {
        void test(shortNS::test &test) {}
        void test1(shortNS::test &test) {}
        void test2(shortNS::test &test1, shortNS::test &test2) {}
    };
}
#undef shortNS

, , "shortNS", "test:: test1", . , , - , , , , .

, , we #undef shortNS, "shortNS" "test:: test1". . shortNS "" .

.

:

  • . ( ?).
  • , .
  • "namespace a = b:: c"
  • "using namespace"
  • (, "using namespace" )

:

  • , .
  • #define #undef, , / .
  • #undef, / , .
  • .
  • , , .

In short, if you like macros and don't mind pulling your hair out, trying to debug it when it goes wrong, go ahead. A preprocessor is a very, very powerful thing, but as if sticking a little C4 on your foot and crushing the keyboard to set a timer, you don’t know when it is going to knock your foot out.

0
source

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


All Articles