Search code examples
c++literalssize-t

Initialize integer literal to std::size_t


There are known ways to manipulate the type of an integer literal

0L;  // long
3U;  // unsigned integer
1LL; // long long

What I need is a way to initialize an integer literal to std::size_t. I supposed that doing

2U; // unsigned int

would be enough, but I still get a compiler error when calling a function template that expects two arguments of the same integral type, e.g.,

template <class T> const T& func(const T& a, const T& b);

gives

no matching function to call for func(unsigned int, size_t)

I know/verified that explicitly casting the argument, say by doing static_cast<std::size_t>(1), solves the problem but is there a simpler way to create the appropriate type, like I can do for the other types mentioned above?


Solution

  • Starting from C++23 you can use the uz or UZ literal for size_t.

    auto size = 42uz;
    static_assert(std::is_same_v<decltype(size), std::size_t>);
    

    Paper: P0330R8
    cppreference: Integer literals