fork download
  1. #include <iostream>
  2. #include <type_traits>
  3. #include <vector>
  4. #include <iostream>
  5. #include <set>
  6.  
  7. template<typename T, typename Iterator, typename=void>
  8. struct is_iterator_of_type: std::false_type {};
  9.  
  10. template<typename T, typename Iterator>
  11. struct is_iterator_of_type<
  12. T,
  13. Iterator,
  14. typename std::enable_if<
  15. std::is_same<
  16. T,
  17. typename std::iterator_traits< Iterator >::value_type
  18. >::value
  19. >::type
  20. >: std::true_type {};
  21.  
  22. void test1() {
  23. std::cout << is_iterator_of_type<int, std::vector<int>::iterator>::value << "\n";
  24. }
  25. template<typename T, typename Container>
  26. auto foo(Container const&) -> typename std::enable_if< is_iterator_of_type<T, typename Container::iterator>::value >::type
  27. {
  28. std::cout << "Container of int\n";
  29. }
  30. template<typename T>
  31. void foo(...)
  32. {
  33. std::cout << "No match\n";
  34. }
  35. void test2() {
  36. std::vector<int> test;
  37. foo<int>(test);
  38. foo<int>(test.begin());
  39. foo<int>(std::set<int>());
  40. }
  41. template<typename Container>
  42. auto operator<<( std::ostream& stream, Container const& c ) ->
  43. typename std::enable_if< is_iterator_of_type<int, typename Container::iterator>::value, std::ostream& >::type
  44. {
  45. stream << "int container\n";
  46. }
  47. void test3() {
  48. std::vector<int> test;
  49. std::cout << test;
  50. std::set<int> bar;
  51. std::cout << bar;
  52. }
  53. template<typename Container>
  54. auto operator<<( std::ostream& stream, Container const& c ) ->
  55. typename std::enable_if< is_iterator_of_type<double, typename Container::iterator>::value, std::ostream& >::type
  56. {
  57. stream << "double container\n";
  58. }
  59. void test4() {
  60. std::vector<int> test;
  61. std::cout << test;
  62. std::set<int> bar;
  63. std::cout << bar;
  64. std::vector<double> dtest;
  65. std::cout << dtest;
  66. }
  67. void test5() {
  68. std::vector<bool> test;
  69. // does not compile (naturall):
  70. // std::cout << test;
  71. }
  72. template<typename Container>
  73. auto operator<<( std::ostream& stream, Container const& c ) ->
  74. typename std::enable_if< is_iterator_of_type<bool, typename Container::iterator>::value, std::ostream& >::type
  75. {
  76. stream << "bool container\n";
  77. }
  78. void test6() {
  79. std::vector<bool> test;
  80. // now compiles:
  81. std::cout << test;
  82. }
  83. int main() {
  84. test1();
  85. test2();
  86. test3();
  87. test4();
  88. test5();
  89. test6();
  90. }
  91.  
  92.  
Success #stdin #stdout 0s 2884KB
stdin
Standard input is empty
stdout
1
Container of int
No match
Container of int
int container
int container
int container
int container
double container
bool container