User literals(C++11)
Channel
C++Weekly
Topics
What topics are important to cover for this episode?
User-literals and use-cases for user-literals. Such as memory-size user-literals.
// namespace My::Cool::Library::Literals {
constexpr std::size_t operator""_KiB(unsigned long long int x) {
return 1024ULL * x;
}
constexpr std::size_t operator""_MiB(unsigned long long int x) {
return 1024_KiB * x;
}
constexpr std::size_t operator""_GiB(unsigned long long int x) {
return 1024_MiB * x;
}
constexpr std::size_t operator""_TiB(unsigned long long int x) {
return 1024_GiB * x;
}
constexpr std::size_t operator""_PiB(unsigned long long int x) {
return 1024_TiB * x;
}
// } // namespace My::Cool::Library::Literals
...
using namespace My::Cool::Library::Literals;
...
const std::size_t BufferSize = 8_MiB;
...
std::byte LogBuffer[64_KiB];
...
Config.StackSize = 16_MiB;
...
class Foo {
public:
Foo() : memory_size_(64_MiB) {
...
std::size_t new_size = round_up(old_size, 64_KiB);
...
if( Size >= 1_GiB )
...
BufferThing(std::size_t InitialSize = 1_MiB);
...
const uint8_t BufferSize = 4_GiB;
// warning: implicit conversion from 'size_t' (aka 'unsigned long') to 'const uint8_t' (aka 'const unsigned char') changes value from 4294967296 to 0 [-Wconstant-conversion]
// const uint8_t BufferSize = 4_GiB;
// ~~~~~~~~~~ ^~~~~
Length
5-10 minutes
I've actually planned and recorded this episode at least once, but have never been happy with the results.
One thing that irritates me with user literals is the use of underscore, whereas with chrono_literals we do not!

#include <iostream>
#include <chrono>
int main()
{
using namespace std::chrono_literals;
auto d1 = 250ms;
std::chrono::milliseconds d2 = 1s;
std::cout << "250ms = " << d1.count() << " milliseconds\n"
<< "1s = " << d2.count() << " milliseconds\n";
}
@lefticus do you have any idea why is that?
ud-suffix | - | an identifier, introduced by a literal operator or a literal operator template declaration (see below). All ud-suffixes introduced by a program must begin with the underscore character _. The standard library ud-suffixes do not begin with underscores.
Aaaah, I didn't see this line clearly, now it makes sense why chrono library does not use underscores!
I learned something new today :smile: