fork download
  1. #include <tuple>
  2. #include <utility>
  3. #include <iostream>
  4. #include <string>
  5.  
  6. // usual sequence boilerplate:
  7. template<unsigned... s> struct seq { typedef seq<s...> type; };
  8. template<unsigned max, unsigned... s > struct make_seq:make_seq<max-1, max-1, s...> {};
  9. template<unsigned... s> struct make_seq<0, s...>:seq<s...> {};
  10.  
  11. // RTR object, which wraps a functor F to do return type deduction:
  12. template<template<typename>class F>
  13. struct RTR {
  14. // Stores a `tuple` of arguments, which it forwards to F when cast to anything:
  15. template<typename... Args>
  16. struct worker {
  17. std::tuple<Args...> args;
  18. worker( Args&&... a ):args(std::forward<Args>(a)...) {}
  19. template<typename T, unsigned... s>
  20. T call(seq<s...>) const {
  21. return F<T>()( std::forward<Args>(std::get<s>(args))... );
  22. }
  23. template<typename T>
  24. operator T() const
  25. {
  26. return call<T>(make_seq<sizeof...(Args)>());
  27. }
  28. };
  29. // Here operator() creates a worker to hold the args and do the actual call to F:
  30. template<typename... Args>
  31. worker<Args...> operator()( Args&&... args ) const {
  32. return {std::forward<Args>(args)...};
  33. }
  34. };
  35.  
  36. // We cannot pass function templates around, so instead we require stateless functors:
  37. template<typename T>
  38. struct read {
  39. T operator()( std::istream& in ) const {
  40. T x;
  41. in >> x;
  42. return x;
  43. }
  44. };
  45.  
  46. // and here we introduce reader, a return type deducing wrapper around read:
  47. namespace { RTR<read> reader; }
  48.  
  49. int main()
  50. {
  51. std::istream& in = std::cin;
  52.  
  53. const int integer = reader( in );
  54. const double decimal = reader( in );
  55. const std::string word = reader( in );
  56.  
  57. std::cout << integer << std::endl;
  58. std::cout << decimal << std::endl;
  59. std::cout << word << std::endl;
  60. }
Success #stdin #stdout 0s 3032KB
stdin
42
3.14
hello
stdout
42
3.14
hello