I'd like to use C++17's std::byte type if it's available, and fall back to using unsigned char if not, i.e. something along the lines of
#include <cstddef>
namespace my {
#if SOMETHING
using byte = std::byte;
#else
using byte = unsigned char;
#endif
}
Unfortunately it seems that std::byte didn't come come with the usual feature test macro, so it's not obvious what SOMETHING above should be. (AFAIK the value of __cplusplus for '17 hasn't been set yet, so I can't test for that either.)
So, does anybody know of a way to detect whether std::byte is available on the big three compilers?
If you want to test availability of std::byte introduced by C++17, you should use __cpp_lib_byte macro (full list of feature testing macros is here).
The sample usage:
#include <iostream>
#include <cstddef>
#if __cpp_lib_byte
using byte = std::byte;
#else
using byte = unsigned char;
#endif
int main() {
return 0;
}
For C++17, the value of __cplusplus is 201703L. But that's not super useful.
Instead, you should look at SD-6. This document contains all the feature test macros for all features adopted into C++, and the vendors all agree to follow them. It's possible that an implementation provides a feature but not the macro (e.g. gcc 7.2 supports std::byte but does not provide the macro) and more obviously that an implementation provides a feature and a macro but the feature is buggy, but you should rely on the macro. That's what it's there for.
Note that using unsigned char gives you almost the exact same behavior as std::byte - the only difference being that unsigned char supports extra arithmetic operations. So having an inexact check for std::byte support is okay - as long as you test on some compiler that supports std::byte to verify that you're not doing anything untoward, you're fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With