Skip to content

Instantly share code, notes, and snippets.

@milesrout
Last active November 6, 2016 22:27
Show Gist options
  • Save milesrout/b2d102023a1ef7cd007fb33dadb2f8e5 to your computer and use it in GitHub Desktop.
Save milesrout/b2d102023a1ef7cd007fb33dadb2f8e5 to your computer and use it in GitHub Desktop.
Ever want to just be able to write `512 K` instead of `512 * 1024` or `524288` in code? Well, wish no more.
#include <iostream>
#include <limits>
#include <stdexcept>
#include <exception>
using namespace std;
static const unsigned long long int max_ull
= std::numeric_limits<unsigned long long int>::max();
constexpr unsigned long long int
operator""_K(unsigned long long int value)
{
return (value > max_ull / 1024)
? throw std::range_error("value out of range")
: (value * 1024);
}
constexpr unsigned long long int
operator""_M(unsigned long long int value)
{
return (value > max_ull / (1024 * 1024))
? throw std::range_error("value out of range")
: (value * 1024 * 1024);
}
constexpr unsigned long long int
operator""_G(unsigned long long int value)
{
return (value > max_ull / (1024 * 1024 * 1024))
? throw std::range_error("value out of range")
: (value * 1024 * 1024 * 1024);
}
constexpr unsigned long long int
operator""_T(unsigned long long int value)
{
return (value > max_ull / (1024ull * 1024 * 1024 * 1024))
? throw std::range_error("value out of range")
: (value * 1024 * 1024 * 1024 * 1024);
}
int main() {
std::cout << 512_K << "\n"; // 524288
std::cout << 1_M << "\n"; // 1048576
std::cout << 1_G << "\n"; // 1073741824
std::cout << 1_T << "\n"; // 1099511627776
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment