Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the STL specify the header guards for its headers?

I want to supply some inline convenience functions using std::string in my header alongside with the library functions which use const char *, but I do not want to include <string>. I want to check with #ifdef if <string> is included and provide the convenience functions if this is the case.

Question: Are the names of header guards in STL headers the same for all STL implementations? In Visual Studio 2010, the header guard of <string> is _STRING_.

like image 205
Fabian Avatar asked Dec 01 '22 13:12

Fabian


2 Answers

This is a BAD IDEA™.

Generally, you cannot and shouldn't rely on an implementation detail of a compiler / library1. On top on that, as stated by Fire Lancer in the comments, "having includes have different effects based on order will confuse people" and adds to the wtf/line of your library.

What you could (should?) do is document a macro for the user to define in order to enable your std::string functions:

#ifdef MY_LIBRARY_ENABLE_STRING_FUNCTIONS
void print(std::string message);
#endif // MY_LIBRARY_ENABLE_STRING_FUNCTIONS

If the user wants them, they'll have to:

#define MY_LIBRARY_ENABLE_STRING_FUNCTIONS
#include <my_library>

1) C++17 has the __has_include(<filename>) macro (credit to acraig5075 for learning this to me) which doesn't help as it returns whether an include is available and not if it has been included.

like image 198
YSC Avatar answered Dec 05 '22 07:12

YSC


The most reliable way to check would probably be using sfinae technique.

That being said, DON'T DO THIS, everything screams anti-pattern when you want to differentiate on whether a header has been included or not, or the order of includes.

like image 30
darune Avatar answered Dec 05 '22 06:12

darune