EN VI

C++ - Why does class template argument deduction fail when omitting empty angle brackets?

2024-03-15 04:30:04
C++ - Why does class template argument deduction fail when omitting empty angle brackets?

Why does this compile?

std::uniform_int_distribution<> dis(0, array.size() - 1);

but this fails class template argument deduction?

std::uniform_int_distribution dis(0, array.size() - 1);

What semantic difference am I making by omitting the angle brackets?

Solution:

template< class IntType = int >
class uniform_int_distribution;

The class only has one template parameter and it is int by default.

In std::uniform_int_distribution<> dis(0, array.size() - 1); you are not using class template argument deduction but tell it to use the default so IntType is int.

In std::uniform_int_distribution dis(0, array.size() - 1); you actually do rely on class template argument deduction - but since it fails, it means that 0 and array.size() are of different types. If array is any of any of the container types in the standard library, its type is std::size_t but 0 is int. IntType can therefore not be deduced.

The most probable solution to get the deduction working:

std::uniform_int_distribution dis(std::size_t{0}, array.size() - 1);

A foolproof solution would check what type array.size() - 1 has and initialize the first parameter with that type:

std::uniform_int_distribution dis(decltype(array.size() - 1){}, array.size() - 1);
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login