How do I use feature-test macros to gate code?

Feature-test macros in C++ are used to conditionally compile sections of code depending on whether a specific feature is available in the compiler or not. This allows you to write code that is portable across different compilers and versions of C++. Here's how you can use them effectively:

To check for specific features, you typically use `#if`, `#ifdef`, or `#ifndef` directives along with predefined macros like `__cplusplus` or compiler-specific macros. Below is a practical example:

#include // Check if C++17 is supported #if __cplusplus >= 201703L #define FEATURE_SUPPORTED true #else #define FEATURE_SUPPORTED false #endif int main() { if (FEATURE_SUPPORTED) { std::cout << "C++17 features are supported!" << std::endl; // Code that uses C++17 features } else { std::cout << "C++17 features are not supported." << std::endl; // Code for older C++ standard } return 0; }

C++ feature-test macros conditional compilation portability __cplusplus compiler compatibility