fork(1) download
  1. #include <type_traits>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <iostream>
  5.  
  6. namespace sort_selector {
  7. // Default to using std::sort
  8. template <typename T, typename = void>
  9. struct dispatcher {
  10. template <typename Iterator>
  11. static void sort(Iterator begin, Iterator end) {
  12. std::cout << "Doing std::sort\n";
  13. std::sort(begin, end);
  14. }
  15. };
  16.  
  17. // Use custom radix sort implementation for integral types
  18. template <typename T>
  19. struct dispatcher<T, typename std::enable_if<std::is_integral<T>::value>::type> {
  20. template <typename Iterator>
  21. static void sort(Iterator, Iterator) {
  22. std::cout << "Doing radix\n";
  23. // radix implementation
  24. }
  25. };
  26.  
  27. // Use some other specific stuff for int32_t
  28. template <>
  29. struct dispatcher<int32_t, void> {
  30. template <typename Iterator>
  31. static void sort(Iterator, Iterator) {
  32. std::cout << "Specific overload for int32_t\n";
  33. // Do something
  34. }
  35. };
  36.  
  37. // Dispatch appropriately
  38. template <typename Iterator>
  39. inline void sort(Iterator begin, Iterator end) {
  40. dispatcher<typename std::iterator_traits<Iterator>::value_type>::sort(begin, end);
  41. }
  42. } // namespace sort_selector
  43.  
  44. int main() {
  45. std::vector<double> for_stdsort = {1, 4, 6, 2};
  46. std::vector<int64_t> for_radixsort = {1, 4, 6, 2};
  47. std::array<int32_t, 4> array_for_radixsort = {1, 4, 6, 2};
  48.  
  49. sort_selector::sort(std::begin(for_stdsort), std::end(for_stdsort));
  50. sort_selector::sort(std::begin(for_radixsort), std::end(for_radixsort));
  51. sort_selector::sort(std::begin(array_for_radixsort), std::end(array_for_radixsort));
  52. }
  53.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Doing std::sort
Doing radix
Specific overload for int32_t