Today in our code base found the following line and liked its elegance for writing a memory size. Was wondering for few minutes about how this was compiling.
size_t poolSize = 16 MByte;
One solution is given as my own answer. Any other solutions?
In modern C++ you should define a literal notation, e.g.
auto operator""_MB( unsigned long long const x )
-> long
{ return 1024L*1024L*x; }
Then write
long const poolSize = 16_MB;
Don't use macros, they're Evil™. In so many ways.
Disclaimer: code not touched by compiler's hands.
Of course you should use template metaprogramming for this problem:
#include <iostream>
#include <type_traits>
template<long long N, long long M>
struct is_power_of
{
static constexpr bool value = (N%M != 0)? false : is_power_of<N/M, M>::value;
};
template<long long M>
struct is_power_of<0, M> : public std::false_type { };
template<long long M>
struct is_power_of<1, M> : public std::true_type { };
template<long long N, typename = typename std::enable_if<is_power_of<N, 1024>::value>::type>
struct bytes
{
enum {value = N, next = value * 1024};
template<long long M>
struct compile_time_get
{
enum {value = N*M};
};
static long long run_time_get(long long x) {return N*x;}
};
typedef bytes<1> byte;
typedef bytes<byte::next> kilo_byte;
typedef bytes<kilo_byte::next> mega_byte;
typedef bytes<mega_byte::next> giga_byte;
typedef bytes<giga_byte::next> tera_byte;
typedef bytes<tera_byte::next> peta_byte;
typedef bytes<peta_byte::next> eksa_byte;
int main()
{
std::cout << kilo_byte::compile_time_get<3>::value << std::endl;
int input = 5;
std::cout << mega_byte::run_time_get(input) << std::endl;
}
Output:
3072
5242880
LIVE
If you are going to be doing it a lot, then a user defined literal is the way to go. OTOH, for one-offs (and to support older compilers and other languages), I'd go with the direct:
size_t poolSize = 16ul*1024*1024;
It was a simple and clever use of the good old macros.
#define KByte *1024
#define MByte *1024*1024
#define GByte *1024*1024*1024
So size_t poolSize = 16 MByte;
gets translated into
size_t poolSize = 16 *1024*1024;
All the examples I saw were more like
#define KB 1024
#define MB (1024*1024)
size_t poolSize = 16*MB;
No magic, no questions, just works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With