fork(2) download
  1. #include <istream>
  2. #include <ostream>
  3. #include <iostream>
  4. #include <type_traits>
  5. #include <cstdint>
  6.  
  7. #define ENABLE_IF_INTEGRAL(T)\
  8. typename = typename std::enable_if<std::is_integral<std::decay_t<T>>::value>::type
  9.  
  10. namespace detail{
  11. template<class T, ENABLE_IF_INTEGRAL(T)>
  12. struct wrapper{
  13. T& x;
  14. wrapper(T& xx) : x(xx){};
  15.  
  16. friend std::istream& operator >> (std::istream& is, wrapper<T> w){
  17. auto read = +w.x;
  18. is>>read;
  19. w.x = static_cast<std::decay_t<T>>(read);
  20. if(w.x != read)
  21. is.setstate(std::ios::failbit);
  22. return is;
  23. }
  24. };
  25. }
  26.  
  27. template<class T, ENABLE_IF_INTEGRAL(T)>
  28. auto intoInt(T& x){ return detail::wrapper<T>(x);}
  29.  
  30. template<class T, ENABLE_IF_INTEGRAL(T)>
  31. auto asInt(T x){ return +x; }
  32.  
  33.  
  34. #undef ENABLE_IF_INTEGRAL
  35.  
  36. int main() {
  37. char foo;
  38.  
  39. std::cin>>intoInt(foo);
  40.  
  41. std::cout<< (std::cin.fail() ? "failed":"success")<<std::endl;
  42.  
  43. std::cout << asInt(foo) << '\n';
  44.  
  45. return 0;
  46. }
Success #stdin #stdout 0s 3472KB
stdin
256
stdout
failed
0