D Turner D Turner - 3 years ago 166
C++ Question

Understanding C++ Parameters in random number generator call

I'm going through some examples in a book entitled Mastering C++ Multithreading and I've come across some code that I don't fully understand.

In this function a random number generator wrapper function I don't understand the parameters.

int randGen(const int& min, const int& max){

static thread_local mt19937 generator(hash<thread::id>() (this_thread::get_id()));

uniform_int_distribution<int> distribution(min, max);

return distribution(generator);

The code I don't understand is the parameters in the generator function call

hash<thread::id>() (this_thread::get_id())

a function taking in the return value from

Any help would be much appreciated, or if I need to supply more info. plz just shout.

Answer Source

With hash<thread::id>() you create an object of the std::hash class template.

Then you call that objects operator() function, passing this_thread::get_id() as argument.

If we split it up, it might be easier to understand:

hash<thread::id> my_hash;  // Create object
my_hash(this_thread::get_id());  // Use the function call operator

The last, using the function call operator, it equal to

my_hash.operator()(this_thread::get_id());  // Use the function call operator

The result of the function call operator is then used as argument to the constructor of the generator object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download