fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <type_traits> //needed for enable_if?
  4. using namespace std;
  5.  
  6. template<class T> struct supports_iteration
  7. {
  8. private:
  9. typedef char yes[1];
  10. typedef char no[2];
  11. template <class C> static yes& foo(typename C::iterator*);
  12. template <class C> static no& foo(...);
  13. public:
  14. static constexpr bool value = sizeof(foo<T>(0)) == sizeof(yes);
  15. };
  16.  
  17.  
  18. template<template <class, class> class C, class T, class A>
  19. void DoSomething(C<T,A>& val)
  20. {
  21. T* pT;
  22. cout << "did something!\n";
  23. }
  24.  
  25. template<template <class, class> class C, class T, class A>
  26. void DoSomethingSmartly(
  27. typename std::enable_if<
  28. supports_iteration<
  29. C<T,A>
  30. >::value
  31. >::type& val)
  32. {
  33. T* pT;
  34. cout << "did something smartly!\n";
  35. }
  36.  
  37. template<template <class, class> class C, class T, class A,
  38. typename = decltype(
  39. declval<C<T,A>>().size()
  40. ,void()
  41. )
  42. >
  43. void DoSomethingReallySmartly(C<T,A>& val)
  44. {
  45. T* pT;
  46. cout << "did something really smartly!\n";
  47. }
  48.  
  49. int main() {
  50. // your code goes here
  51. vector<int> v{1,2,3,4,5};
  52. DoSomething(v);
  53. cout << "vector<int> supports_iteration? " <<
  54. boolalpha << supports_iteration<decltype(v)>::value << "!" << endl;
  55. //DoSomethingSmartly(v);// - fails!!
  56. //template argument deduction/substitution failed:
  57. //couldn't deduce template parameter ‘template<class, class> class C’ DoSomethingSmartly(v);
  58. DoSomethingReallySmartly(v);
  59. return 0;
  60. }
  61.  
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
did something!
vector<int> supports_iteration? true!
did something really smartly!