Monday, July 31, 2017

C++11: User-defined Literals

A User-defined literal is a constant that has a suffix that a class can define an operator for to handle. Here is an example:
#include &ltcmath&gt
#include &ltiostream&gt
int operator ""_z(unsigned long long i) { return (int)std::pow(2, i); }
int main()
  std::cout << 5_z << std::endl;
  return 0;
// Output: 32

1 comment:

  1. The code compiles on Visual Studio 2015. For it to compile on g++, a space is needed between the "" and the _ in the operator name. Also g++ needs the compile switch "-std=gnu++1"