fork download
  1. // needed for is_same
  2. #include <type_traits>
  3. #include <tuple>
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. // this should be an inner and private metafunction of exists_type
  9. // I put here for clarity
  10. template<typename T, typename Tuple, const int index>
  11. struct exists_type_index
  12. {
  13. static const bool value =
  14. is_same < T, typename tuple_element<index, Tuple>::type >::value ||
  15. exists_type_index<T, Tuple, index-1>::value;
  16. };
  17.  
  18. // stop the recursion when reach the first element
  19. template<typename T, typename Tuple>
  20. struct exists_type_index<T, Tuple, 0>
  21. {
  22. static const bool value = is_same < T, typename tuple_element<0, Tuple>::type >::value;
  23. };
  24.  
  25. // exists_type metafunction (clients call this)
  26. template<typename T, typename Tuple>
  27. struct exists_type
  28. {
  29. static const bool value = exists_type_index<T, Tuple, tuple_size<Tuple>::value-1>::value;
  30. };
  31.  
  32. ////////////////////////// Executor
  33.  
  34. template<bool b>
  35. struct Executor
  36. {
  37. template<typename T>
  38. static void execute(T&&)
  39. {
  40. cout << "General case" << endl;
  41. }
  42. };
  43.  
  44. template<>
  45. struct Executor <true>
  46. {
  47. template<typename T>
  48. static void execute(T&&)
  49. {
  50. cout << "Specific case" << endl;
  51. }
  52. };
  53.  
  54. // clients call this
  55. template<typename Tuple>
  56. struct MultiTypeDispatcher
  57. {
  58. template<typename T>
  59. void function( T&& t )
  60. {
  61. Executor<exists_type<T, Tuple>::value>::execute(forward<T>(t));
  62. }
  63. };
  64.  
  65.  
  66. int main()
  67. {
  68. MultiTypeDispatcher< tuple<int, float, string> > dispatcher;
  69.  
  70. dispatcher.function(string("hello!")); // Specific case!
  71. dispatcher.function(1.0f); // Specific case!
  72. dispatcher.function(1.0); // General case!
  73.  
  74. return 0;
  75. }
Success #stdin #stdout 0s 3016KB
stdin
Standard input is empty
stdout
Specific case
Specific case
General case