How do I pass a C++11 random number generator to a function?

后端 未结 4 2261
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 20:17

Do they all inherit from a base class? Do I have to use templates?

(I am referring to these http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15319/)

4条回答
  •  借酒劲吻你
    2020-12-15 20:40

    What worked for me was using an std::function:

    #include 
    #include 
    
    void exampleFunction(std::function rnd) {
        auto randomNumber = rnd();
    }
    
    std::minstd_rand rnd;
    exampleFunction([&rnd](){ return rnd(); });
    
    // This won't work as it passes a copy of the object, so you end up with the same
    // sequence of numbers on every call.
    exampleFunction(rnd);
    

    You're not really passing around the random object, just a method to call the object's operator (), but it achieves the same effect.

    Note that here the precision of the random number generator's return value may be reduced as the std::function is declared as returning an int, so you may want to use a different data type instead of int depending on your need for precision.

提交回复
热议问题