fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. // Identify the type of element in given range type.
  5. template<typename Range> struct range_elem {
  6. typedef typename std::decay<decltype(*std::begin(std::declval<Range &>()))>::type type;
  7. };
  8.  
  9. // Count the number of elements in range matching value.
  10. template<typename Range>
  11. int count(const Range& range, typename range_elem<Range>::type value) {
  12. int n = 0;
  13. for (const auto& e : range) { if (e==value) n++; }
  14. return n;
  15. }
  16.  
  17. int main() {
  18. // This compiles OK.
  19. std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(3);
  20. std::cerr << count(vec, 2) << "\n";
  21. //
  22. int ar[3] = {1,2,3};
  23. // This compiles OK.
  24. {
  25. int n = 0;
  26. for (const auto& e : ar) { if (e==2) n++; }
  27. std::cerr << n << "\n";
  28. }
  29. // This fails to compile on gcc 4.8.1;
  30. // error: no matching function for call to 'begin(int [3])'
  31. std::cerr << count(ar, 2) << "\n";
  32. return 0;
  33. }
Success #stdin #stdout #stderr 0s 3468KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
1
1
1