tuple-apply.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //#define CXXOMFORT_NOTICES 1
  2. #include <cxxomfort/cxxomfort.hpp>
  3. #include <cxxomfort/tuple.hpp>
  4. #include <cxxomfort/library/foreach.hpp>
  5. #include <cxxomfort/library/tuple.hpp>
  6. #include <cxxomfort/library/operatorit.hpp>
  7. #include <cxxomfort/functional.hpp> // ptr_fun, mem_fn
  8. #include <iostream>
  9. #include <ctime>
  10. #include <cstdio> // printf
  11. #include <cmath>
  12. #include <string> // string::substr
  13. #include <vector>
  14. #if (!defined(__cpp_lib_apply))
  15. #error "std::apply not detected or implemented"
  16. #endif
  17. //
  18. // booh
  19. //
  20. struct booh {
  21. booh() : _v(rand()) {}
  22. int value () const { return _v; }
  23. booh& operator++() {
  24. std::cout<< "[booh++!]"<< std::endl;
  25. return *this;
  26. }
  27. int _v;
  28. };
  29. //
  30. // wrapper that gives a std::string a ++ operator
  31. //
  32. struct ppstring
  33. : std::string {
  34. typedef std::string base_type;
  35. ppstring (std::string const& s) : std::string(s) {}
  36. ppstring& operator++ () {
  37. static_cast<base_type*>(this)->append("!");
  38. return *this;
  39. }
  40. };
  41. std::ostream& operator<< (std::ostream& os, booh const& b) {
  42. return os<< b.value();
  43. }
  44. static const char* m [] = {"Hello World", "0123456789abcdef", "H€llo", "Hellø", "Bye~"};
  45. inline std::string string_substr (std::string const& S, size_t from, size_t count) {
  46. return S.substr(from,count);
  47. }
  48. typedef std::tuple<float,ppstring,int,booh> TupleT;
  49. // a functor tha operates on the components of a TupleT
  50. struct DuplT {
  51. typedef void result_type;
  52. void operator() (float& f, ppstring& p, int& i, booh& b) {
  53. ++f;
  54. p+= p;
  55. i-= 10;
  56. (void)b;
  57. }
  58. } dupfn = {};
  59. int main () {
  60. using namespace std;
  61. srand(time(0));
  62. TupleT tt (-2.0727f, string("Hello World!"), -1, booh());
  63. cout<< "Values of tuple: "<< endl;
  64. cout<< "float: "<< get<float>(tt)<< ", string: "<< get<ppstring>(tt)<< ", int: "<< get<int>(tt)<< ", booh: "<< get<booh>(tt)<< endl;
  65. cout<< "apply: "<< endl;
  66. //cxxomfort::functional::preincrement<void> p;
  67. cout<< "We'll pass now the tuple as arguments to 'dupfn' \n "
  68. << "which performs the following tasks: \n"
  69. << " * decrements each numeric argument\n"
  70. << " * duplicates each string argument\n"
  71. << " * leaves booh alone (booh...)\n"
  72. << endl;
  73. apply( dupfn, tt);
  74. cout<< "float: "<< get<float>(tt)<< ", string: "<< get<ppstring>(tt)<< ", int: "<< get<int>(tt)<< ", booh: "<< get<booh>(tt)<< endl;
  75. }