User-defined literals allow you to write C++ code for parsing custom syntax.
The parsing code must be constexpr
so that it can be evaluated at compile time.
C++ 14 already syntax for writing numbers in binary:
// 21 in binary syntax
int number = 0b0001'0101;
We can implement similar functionality ourselves:
https://codeeval.dev/gist/fe86de3b2a3f5071478225350e1126ac
https://codeeval.dev/gist/e02565f5e2f4fdc21da38bc51d6f53a0
Those following duration user literals are declared in the namespace
std::literals::chrono_literals
, where both literals
and chrono_literals
are inline namespaces. Access to these operators can be gained with using namespace std::literals
, using namespace std::chrono_literals
, and using namespace std::literals::chrono_literals
.
https://codeeval.dev/gist/2cdc964488d0f63ba6b4d6ee1ed1397f
Those following string user literals are declared in the namespace
std::literals::string_literals
, where both literals
and string_literals
are inline namespaces. Access to these operators can be gained with using namespace std::literals
, using namespace std::string_literals
, and using namespace std::literals::string_literals
.
https://codeeval.dev/gist/9532dec654e0c1bf95107e9f48daa709
Literal string may containing \\0
std::string s1 = "foo\\0\\0bar"; // constructor from C-string: results in "foo"s
std::string s2 = "foo\\0\\0bar"s; // That string contains 2 '\\0' in its middle
Those following complex user literals are declared in the namespace
std::literals::complex_literals
, where both literals
and complex_literals
are inline namespaces. Access to these operators can be gained with using namespace std::literals
, using namespace std::complex_literals
, and using namespace std::literals::complex_literals
.