Doug Mika <
doug...@gmail.com> wrote in
news:bb027818-8e62-4622...@googlegroups.com:
> The std::search function is a template function, however to invoke it,
> we do NOT need to specify the template parameters!! ie. we can call
> the function as follows: std::search (haystack.begin(),
> haystack.end(), needle1, needle1+4);
>
> So the question is, why in the following program that I have attached,
> why must I write
>
> size_t nNumEvenElements = count_if(vecIntegers.begin(),
> vecIntegers.end(), IsEven<int>);
>
> why can't I write
[...]
> template <typename elementType>
> bool IsEven (const elementType& number){
> return ((number % 2)==0);
> }
[...]
>
> size_t nNumEvenElements = count_if(vecIntegers.begin(),
> vecIntegers.end(), IsEven);
The template which you need to explicitly instantiate is not
std::count_if(), but your own IsEven. If you don't like to do this, then
one option is simply to not use a template.
More to the point, template parameters can be omitted if the compiler is
able to deduce them from the types of passed function arguments. In the
above line no arguments are passed to IsEven, so the compiler cannot
deduce its template parameters. So it does not know what type is the
argument for the count_if and so in turn it is not able to deduce the
template paramters for the count_if itself.
You can "fix" this by specifying the count_if template parameters
explicitly. Then you don't need to specify them for IsEven:
size_t nNumEvenElements =
count_if<vector<int>::iterator, bool (*)(const int&)>(
vecIntegers.begin(), vecIntegers.end(), IsEven);
hth
Paavo