3

I'm trying to learn new features/gimmicks of c++17, but then I got to std::byte and for some unknown reason I can't seem to be able to compile even most basic "hello world" type program with the type.

entire program:

#include <cstddef>
int main(int argc, char* argv[])
{
    std::byte byte;
    return 0;
}

compilation command:

g++ ./main.cpp

But the output is always:

./main.cpp: In function ‘int main(int, char**)’:
./main.cpp:4:10: error: ‘byte’ is not a member of ‘std’
    std::byte byte;

I work on Ubuntu 18.04 with gcc 7.4.0. I have checked "/usr/include/c++/7.4.0/" and header file cstddef is there and byte seems to be defined.

I have also tried to use clang:

clang++ ./main.cpp

But the result was same. At this point I can only think that cstddef is corrupted/bugged. Are there any solutions to this?

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
DFDark
  • 219
  • 1
  • 2
  • 14

2 Answers2

10

As πάντα ῥεῖ pointed out in comment I was missing c++17 compile flag. Right compilation command:

g++ -std=c++17 ./main.cpp
DFDark
  • 219
  • 1
  • 2
  • 14
2

If you use clang 5.0 (even with -std=c++17 flag) the same error occur. In that case, to solve this you need to upgrade to clang 6.

A temporay and quick workaround is possible (but not recommanded since it plays with std namespace), it could be something like:

#if defined(__clang__) && __cplusplus >= 201703L && __clang_major__ < 6
// This is a minimal workaround for clang 5.0 with missing std::byte type
namespace std {
enum class byte : unsigned char {};
}
#endif
Pascal H.
  • 1,431
  • 8
  • 18
  • It's a reasonable workaround for a personal project, but still, it should come with a warning: "_It is undefined behavior to add declarations or definitions to namespace std or to any namespace nested within std, with a few exceptions ..._". – Ted Lyngmo Feb 02 '20 at 01:30
  • 1
    Good remark. I'm perfectly aware that it is only a workaround not a *good* solution. In that case, it was to illustrate that sometimes even with a proper C++17 flag, the same problem can occur. I will reword my answer to remove this ambiguity. – Pascal H. Feb 02 '20 at 12:50