fork download
  1. # include <iostream>
  2. # include <random>
  3. # include <type_traits>
  4. # include <ctime>
  5.  
  6. namespace detail {
  7. template <typename tType>
  8. struct Select_DistT {
  9. typedef typename std::conditional<
  10. std::is_integral<tType>::value,
  11. std::uniform_int_distribution<tType>,
  12. std::uniform_real_distribution<tType>
  13. >::type type;
  14. };
  15. }
  16.  
  17. template<typename tType, class DistT = typename detail::Select_DistT<tType>::type>
  18. class Random
  19. {
  20. std::default_random_engine mEngine;
  21. DistT mDistribution;
  22. public:
  23. Random(tType iMin, tType iMax) :
  24. mEngine(time(nullptr)),
  25. mDistribution(iMin, iMax)
  26. { }
  27.  
  28. tType operator()()
  29. {
  30. return mDistribution(mEngine);
  31. }
  32. };
  33.  
  34. int main()
  35. {
  36. Random<int> aRandomInt(0, 4);
  37. for(int i=0; i < 10; ++i)
  38. {
  39. std::cout << aRandomInt() << '\n';
  40. }
  41.  
  42. Random<double> aRandomDouble(0, 4);
  43. for(int i=0; i < 10; ++i)
  44. {
  45. std::cout << aRandomDouble() << '\n';
  46. }
  47.  
  48. return 0;
  49. }
  50.  
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
2
1
0
3
3
1
1
1
3
2
1.24878
2.82828
0.958006
1.27204
1.73492
0.484948
3.75761
0.678754
2.62261
1.05893