fork(3) download
  1. #include <iostream>
  2. #include <limits>
  3.  
  4. template<typename Desired, typename Given>
  5. constexpr Desired narrow_cast(Given arg) {
  6. static_assert(std::is_integral<Desired>::value, "Only integer types are supported");
  7. static_assert(std::is_integral<Given>::value, "Only integer types are supported");
  8.  
  9. auto min = std::numeric_limits<Desired>::min();
  10. auto max = std::numeric_limits<Desired>::max();
  11.  
  12. auto different_signs = std::is_signed<Given>::value xor std::is_signed<Desired>::value;
  13. if(sizeof(Desired) == sizeof(Given) && different_signs && arg < 0) {
  14. return 0;
  15. }
  16.  
  17. return
  18. min > arg? min:
  19. max < arg? max:
  20. arg;
  21. }
  22.  
  23. int main() {
  24. std::cout << narrow_cast<short>(100000) << std::endl;
  25. std::cout << narrow_cast<unsigned short>(100000) << std::endl;
  26. std::cout << narrow_cast<unsigned short>(-100000) << std::endl;
  27. std::cout << narrow_cast<int>(-1) << std::endl;
  28. std::cout << narrow_cast<unsigned int>(-1) << std::endl;
  29. std::cout << narrow_cast<unsigned short>(-1) << std::endl;
  30. return 0;
  31. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
32767
65535
0
-1
0
0