Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with painfully long namespace names in headers

Is there anything that can be done about looong symbols that need to be referenced in header files, e.g. ABDEFGHIJ::ZXCBVB::AWEDADSDEM::GFGBKGDF::Tools::Item? I know in header files you aren't supposed to using using because it messes up anybody who includes it.

The only working feature that cleans up after itself that I can even think of would be #define+#undef but that seems terrible.

Is there a new feature that solves this that I'm not aware of? I'm also interested in any popular proposals. Maybe using with a bracketed block syntax, to let me restrict the effect to just my header...?

like image 977
VoidStar Avatar asked Aug 26 '15 21:08

VoidStar


1 Answers

It's not good practice to have a using namespace using directive at global scope in a header file. There are a number of less drastic things you can do that are fairly benign however.

  • Inside an inline or template function in a header, you can use a using directive without affecting anyone else. This saves you having to qualify all the names in a non-trivial function body.
  • As Maksim Solovjov suggests, you can use namespace aliases to cut down on typing, with the caveat that a namespace alias at global scope will introduce that alias to anyone including your header so that may not be desirable.
  • C++11 introduced type aliases and alias templates which can be used in a header at class scope, function scope or namespace scope (you may still want to avoid using them at global scope) to give a shorter name to types. This is particularly useful when dealing with template types with long names like e.g. std::map<std::string, std::vector<std::function<float(float)>>>
  • C++11 and 14 type deduction through the auto keyword can greatly reduce the need to name long types in headers, whether function return types, local variables or parameters to lambdas.
  • C++11 decltype can also be useful to avoid saying the names of long types in certain situations.
like image 195
mattnewport Avatar answered Sep 30 '22 02:09

mattnewport