random 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // <experimental/random> -*- C++ -*-
  2. // Copyright (C) 2015-2018 Free Software Foundation, Inc.
  3. //
  4. // This file is part of the GNU ISO C++ Library. This library is free
  5. // software; you can redistribute it and/or modify it under the
  6. // terms of the GNU General Public License as published by the
  7. // Free Software Foundation; either version 3, or (at your option)
  8. // any later version.
  9. // This library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. // Under Section 7 of GPL version 3, you are granted additional
  14. // permissions described in the GCC Runtime Library Exception, version
  15. // 3.1, as published by the Free Software Foundation.
  16. // You should have received a copy of the GNU General Public License and
  17. // a copy of the GCC Runtime Library Exception along with this program;
  18. // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. // <http://www.gnu.org/licenses/>.
  20. /** @file experimental/random
  21. * This is a TS C++ Library header.
  22. */
  23. #ifndef _GLIBCXX_EXPERIMENTAL_RANDOM
  24. #define _GLIBCXX_EXPERIMENTAL_RANDOM 1
  25. #include <random>
  26. #include <experimental/bits/lfts_config.h>
  27. namespace std {
  28. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  29. namespace experimental {
  30. inline namespace fundamentals_v2 {
  31. #define __cpp_lib_experimental_randint 201511
  32. inline std::default_random_engine&
  33. _S_randint_engine()
  34. {
  35. static thread_local default_random_engine __eng{random_device{}()};
  36. return __eng;
  37. }
  38. // 13.2.2.1, Function template randint
  39. template<typename _IntType>
  40. inline _IntType
  41. randint(_IntType __a, _IntType __b)
  42. {
  43. static_assert(is_integral<_IntType>::value && sizeof(_IntType) > 1,
  44. "argument must be an integer type");
  45. using _Dist = std::uniform_int_distribution<_IntType>;
  46. // This relies on the fact our uniform_int_distribution is stateless,
  47. // otherwise we'd need a static thread_local _Dist and pass it
  48. // _Dist::param_type{__a, __b}.
  49. return _Dist(__a, __b)(_S_randint_engine());
  50. }
  51. inline void
  52. reseed()
  53. {
  54. _S_randint_engine().seed(random_device{}());
  55. }
  56. inline void
  57. reseed(default_random_engine::result_type __value)
  58. {
  59. _S_randint_engine().seed(__value);
  60. }
  61. } // namespace fundamentals_v2
  62. } // namespace experimental
  63. _GLIBCXX_END_NAMESPACE_VERSION
  64. } // namespace std
  65. #endif