How-To use variable sized integers

C++ provides integer types of many sizes, but none of them are variably sized. Even though this library provides a liberate::types::varint type, let’s be honest, it’s just an int64_t in disguise.

So what’s the ruckus all about?

Most of all, it’s about how to encode integer values in file formats or on the network. But in C++ code, it’d be convenient to have a type that signals that a value is to be encoded in this way.

Using varint
 1#include <liberate/types/varint.h>
 2
 3liberate::types::varint x = 12;
 4x += 3;
 5
 6// or simpler
 7
 8using namespace liberate::types::literals;
 9
10auto y = 12_var;

The resulting type can be used like an integral type, but C++ will treat it as distinct from its int64_t base. This is because it is technically an enumeration derived from varint_base, and with a bunch of operators defined.

For the most part, you do not need to worry about this. Just remember that using the varint type helps when you want to encode integer values in variable length.