Search code examples
c++templatesgenerate

Using generate to fill list in template class c++


I am working on a project where i have a template class in which i have a List. This function i have included is meant to fill the list with random numbers. But each time i run it it says that "term does not evaluate to a function taking 0 arguments" and what i have understood is that i cant use a function that returns a value in Generate.

How do i make Generator and Random to functors? Is there a way to do this without it?

template<typename T>
void ListManipulator<T>::fillList()
{
    std::uniform_real_distribution<double> random(1000, 2000);
    std::default_random_engine generator(static_cast<unsigned>(std::time(0)));

    std::generate(theList.begin(), theList.end(), random(generator));

Solution

  • Try the following:

    std::uniform_real_distribution<double> random(1000, 2000);
    std::default_random_engine generator(static_cast<unsigned>(std::time(0)));
    
    std::generate(theList.begin(), theList.end(), 
        [&random, &generator]{ return random(generator); });
    

    std::generate requires a generator which is a function with a signature:

    Ret fun();
    

    And you provide not a function at all, but a double value.