I stumble upon a compilation error which I don't understand. In the following code snippet the option (1) does not compile. But the second option does. I thought both should give the same result. Can someone explain me what my mistake is here?
#include <string>
#include <cctype>
#include <algorithm>
int main() {
std::string str{"bla"};
std::count_if(str.begin(), str.end(), std::isupper); // (1)
std::count_if(str.begin(), str.end(), ::isupper); // (2)
}
The error message:
../src/main.cpp: In function ‘int main()’:
../src/main.cpp:7:18: error: no matching function for call to ‘count_if(std::__cxx11::basic_string<char>::iterator, std::__cxx11::basic_string<char>::iterator, <unresolved overloaded function type>)’
7 | std::count_if(str.begin(), str.end(), std::isupper); // (1)
| ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/11.1.0/algorithm:62,
from ../src/main.cpp:3:
/usr/include/c++/11.1.0/bits/stl_algo.h:4083:5: note: candidate: ‘template<class _IIter, class _Predicate> typename std::iterator_traits< <template-parameter-1-1> >::difference_type std::count_if(_IIter, _IIter, _Predicate)’
4083 | count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred)
| ^~~~~~~~
/usr/include/c++/11.1.0/bits/stl_algo.h:4083:5: note: template argument deduction/substitution failed:
../src/main.cpp:7:18: note: couldn’t deduce template parameter ‘_Predicate’
7 | std::count_if(str.begin(), str.end(), std::isupper); // (1)
| ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/11.1.0/algorithm:74,
from ../src/main.cpp:3:
/usr/include/c++/11.1.0/pstl/glue_algorithm_defs.h:106:1: note: candidate: ‘template<class _ExecutionPolicy, class _ForwardIterator, class _Predicate> __pstl::__internal::__enable_if_execution_policy<_ExecutionPolicy, typename std::iterator_traits<_II>::difference_type> std::count_if(_ExecutionPolicy&&, _ForwardIterator, _ForwardIterator, _Predicate)’
106 | count_if(_ExecutionPolicy&& __exec, _ForwardIterator __first, _ForwardIterator __last, _Predicate __pred);
| ^~~~~~~~
/usr/include/c++/11.1.0/pstl/glue_algorithm_defs.h:106:1: note: template argument deduction/substitution failed:
../src/main.cpp:7:18: note: candidate expects 4 arguments, 3 provided
7 | std::count_if(str.begin(), str.end(), std::isupper); // (1)
| ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~