How to use auto keyword to assign a variable of type uint32_t or uint64_t in C++

Viewed 1784

Consider auto var = 5u;. Here, I am using suffix u, so that var will be deduced as unsigned int. Is there any way to achieve something similar for uint32_t or uint64_t types? Is there any suffix in C++11 or C++14?

2 Answers

I'm assuming you're working with the AAA style suggested by Herb Sutter.

In that case, a nice solution is to simply write:

auto variable_name = uint64_t{ 5000000000 };

This is clear, consistent, and explicitly typed with no nasty C-preprocessor necessary.


Edit: if you want to be absolutely sure when using a literal, an appropriate suffix can be added to the integer literal to ensure great enough range, while still explicitly typing the variable.

You could always define your own suffix

#include <cstdint>
#include <type_traits>

uint32_t operator ""_u32 (unsigned long long v) { return uint32_t (v); } 

int main ()
{
    auto v = 10_u32;

    static_assert (std::is_same <decltype (v), uint32_t>::value);
}
Related