Can I use #ifdef safely to find out if the std header is C ++ enabled?

First of all, I read this question: Is there a way to detect portable that the standard header is enabled using macros?

And I want to know: how safe is it to use #ifdef for the detection task if the std C ++ header is included, as in the code below:

 namespace overwrite { using byte = unsigned char; template <bool safeMode = true, typename generic> void withZeros( generic *toBeOverwriten, size_t length = 1 ) { // do stuff } #ifdef _GLIBCXX_RANDOM // found this macro inside <random> template <bool safeMode = true, typename generic> void withRandomData( generic *toBeOverwriten, byte min = 0, byte max = 255 ) { // do stuff expecting <random> to be included } #endif } 

... so I could not just overload some std function as the β€œworst match” as suggested in the answer to the above question, but also compile or not the whole function / section of my header file, depending on the inclusion of some std header .

Isn't it generally safe, as I suspect? If so, are there other ways to detect this in order to do what I want?

As for "Why the hell am I just not including the headline" ...

The code I give as an example of what I'm trying to do is just an example. I had other things in my mind, and I just wanted to know if there is another way to check for the inclusion of headers without checking the macros that you expect to define inside them. Then I remembered this real situation, when I asked myself about it, and I started by asking what I was asking ... because in this case I do not want to include a lot of code ( <random> longer than 20 or 30 LOC) to "support" one function of my header.

+6
source share
1 answer

There is a c++17 suggestion c++17 add the __has_include macro.

The latest version has not yet been published, but was discussed (approved?) At the last standard meeting: https://www.reddit.com/r/cpp/comments/3q4agc/c17_progress_update_oct_2015/

Previous version: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0061r0.html


Until then, I don't think there is a portable way to detect if a header is available. The best thing you can do is check which macro defines the title, given that different libraries have different macros and that even in the same libraries the name can change from revision to revision, since this is an internal macro. This is not so bad if you want to support the main compilers (there are 3 of them) and do not expect your code to be supported in 3-5 years.

Instead of checking the header, if possible, you should check for functions. C++11 further defines the feature testing macros suite:

http://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros

+3
source

All Articles