jeudi 31 janvier 2019

random_device()() work only for initializing data members

This is typical sequence of declarations/definitions for generating random numbers in C++11:

std::random_device rd
std::default_random_engine gen(rd());
std::uniform_int_distribution<> dist(1, 6);

rd is only used for seeding the generator gen, so I am thinking of not defining it in particular. In stead, I would like to use a temporary for this purpose:

int main() {
    std::default_random_engine gen(std::random_device()());
    std::uniform_int_distribution<> dist(1,6);
}

But compiler gave me an error:

function returns function

But this works if I initialize the engine as a data member:

class A
{
public:
    A();
private:
    std::default_random_engine gen;
    std::uniform_int_distribution<> dist;
}

A::A() : gen(std::random_device()()), dist(1) {}

So why can I not use std::random_device()() in normal statement to initialize a random generator but can use it in initializing data members? How to make it working in normal statement? Thanks.

PS: I am working on Windows 10 using Visual Studio 2015.

Aucun commentaire:

Enregistrer un commentaire