Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: compile-time #Include handling if file not found

Tags:

c++

c++17

Mainly I am interested in the case of #include <filesystem>, but also in other experimental features that eventually get rolled into the standard. The issue, as you all know, is that as new C++ features are rolled out (e.g. filesystem in C++17), some compilers might have them implemented as an experimental feature (e.g. GCC 7), while others might have this implemented as a non-experimental feature. I realized that the APIs do change slightly when going from the experimental to the final implementation, but for the sake of the following, suppose that they do not...

Is there is a way to do something like SFINAE to include the correct file. In pseudo code it would look something like this:

#ifdef filesystem
  #include <filesystem>
  using std::filesystem;
#else
  #include <experimental/filesystem>
  using std::experimental::filesystem; 
#endif

I am not aware of any compile-time mechanism that could do something if a file is not found. Is there such a thing?

I am aware of other approaches to solve this, but they all rely on detecting the specific compiler and then declaring a macro which tells you which #include to use. So please do not post a response which is essentially just going to look whether the compiler is, for instance, GCC 7, and then do some handling based on that.

like image 500
bremen_matt Avatar asked Jan 25 '23 19:01

bremen_matt


1 Answers

C++17 introduced the __has_include preprocessor test. You can use that to check for a header's presence:

#if __has_include(<filesystem>)
#  include <filesystem>
#else
//...
#endif
like image 61
StoryTeller - Unslander Monica Avatar answered Jan 30 '23 06:01

StoryTeller - Unslander Monica