Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing the availability of std::byte

Tags:

c++

c++17

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?

like image 804
Tristan Brindle Avatar asked Jun 12 '17 18:06

Tristan Brindle


2 Answers

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; 
}
like image 155
NutCracker Avatar answered Oct 18 '22 04:10

NutCracker


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.

like image 43
Barry Avatar answered Oct 18 '22 05:10

Barry