Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a literal constant like "size_t s = 16 MByte"?

Tags:

c++

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?

like image 975
PermanentGuest Avatar asked Sep 21 '16 17:09

PermanentGuest


5 Answers

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.

like image 160
Cheers and hth. - Alf Avatar answered Oct 31 '22 23:10

Cheers and hth. - Alf


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

like image 25
xinaiz Avatar answered Oct 31 '22 22:10

xinaiz


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;
like image 6
Martin Bonner supports Monica Avatar answered Oct 31 '22 23:10

Martin Bonner supports Monica


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;
like image 5
PermanentGuest Avatar answered Oct 31 '22 23:10

PermanentGuest


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.

like image 2
aragaer Avatar answered Oct 31 '22 23:10

aragaer