Guest User

Untitled

a guest
Oct 23rd, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. #include <gsl/gsl>
  2. #include <iostream>
  3. #include <tuple>
  4. #include <utility>
  5.  
  6. template <typename F>
  7. struct Fold {
  8. F oper;
  9.  
  10. template <typename T>
  11. struct Wrapper {
  12. F oper;
  13. T value;
  14.  
  15. template <typename Fs, typename Ts>
  16. constexpr Wrapper(Fs&& oper, Ts&& value) :
  17. oper(std::forward<Fs>(oper)), value(std::forward<Ts>(value))
  18. {
  19. // Do nothing
  20. }
  21.  
  22. template <typename Ts, typename W>
  23. constexpr friend auto operator+(Ts&& value, const Wrapper<W>& wrapper) {
  24. return wrapper.oper(std::forward<Ts>(value), wrapper.value);
  25. }
  26. };
  27.  
  28. template <typename Fs>
  29. constexpr Fold(Fs&& oper) : oper(std::forward<Fs>(oper)) {
  30. // DO Nothing
  31. }
  32.  
  33. template <typename T, typename... Ts>
  34. constexpr auto operator()(T&& initial, Ts&&... values) const {
  35. return impl(
  36. std::forward<T>(initial),
  37. std::make_tuple(Wrapper<Ts>(oper, std::forward<Ts>(values))...),
  38. std::make_index_sequence<sizeof...(Ts)>{});
  39. }
  40.  
  41. template <typename T, typename TupleT, size_t... Idx>
  42. constexpr auto impl(
  43. T&& initial,
  44. TupleT&& tuple,
  45. std::index_sequence<Idx...>) const
  46. {
  47. return (std::forward<T>(initial) + ... + std::get<Idx>(tuple));
  48. }
  49. };
  50.  
  51. template <typename F>
  52. constexpr auto fold(F&& binary) {
  53. return Fold<F>(std::forward<F>(binary));
  54. }
  55.  
  56. template <typename T, typename U>
  57. constexpr auto min(const T& a, const U& b) -> std::common_type_t<T, U> {
  58. return a < b ? a : b;
  59. }
  60.  
  61. constexpr int add(int a, int b) {
  62. return a + b;
  63. }
  64.  
  65. int main() {
  66. std::cout << fold(min<int, int>)(1, 3, 2, 5, 4) << std::endl;
  67. std::cout << fold(min<std::string, std::string>)("abc", "zef", "qwe")
  68. << std::endl;
  69.  
  70. constexpr int result = fold(add)(1, 2, 3, 4, 5);
  71. std::cout << result << std::endl;
  72.  
  73. return 0;
  74. }
Add Comment
Please, Sign In to add comment