fork(3) download
  1. /*
  2. Author: Peter R. Bloomfield
  3. Website: avidinsight.uk
  4.  
  5. Example of using std::conditional<> to select an unsigned integer type based on
  6. size. The size is specified by template parameter.
  7.  
  8. Note that ideone seems to output abbreviated typenames for typeid().name().
  9. Try the code in an offline compiler to see the correct output.
  10. */
  11.  
  12. #include <iostream>
  13. #include <type_traits>
  14. #include <typeinfo>
  15.  
  16. // A template which selects an unsigned integer type with at least the number of
  17. // bytes specified in the template parameter.
  18. template <std::uint8_t T_numBytes>
  19. using UintSelector =
  20. typename std::conditional<T_numBytes == 1, std::uint8_t,
  21. typename std::conditional<T_numBytes == 2, std::uint16_t,
  22. typename std::conditional<T_numBytes == 3 || T_numBytes == 4, std::uint32_t,
  23. std::uint64_t
  24. >::type
  25. >::type
  26. >::type;
  27.  
  28. // A test function which uses RTTI to output the type name.
  29. template <std::uint8_t T_numBytes>
  30. void test()
  31. {
  32. std::cout << static_cast<unsigned int>(T_numBytes) << " => " <<
  33. typeid(UintSelector<T_numBytes>).name() << std::endl;
  34. }
  35.  
  36. int main() {
  37.  
  38. test<1>();
  39. test<2>();
  40. test<3>();
  41. test<4>();
  42. test<5>();
  43. test<6>();
  44. test<7>();
  45. test<8>();
  46. test<9>();
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
1 => h
2 => t
3 => j
4 => j
5 => y
6 => y
7 => y
8 => y
9 => y