my count_if() implementation doesnt work

Hi, I'm having trouble understanding 1 thing so here it is!

1. I created my count_if function
1
2
3
4
5
6
7
8
9
10
11
template<class Iter, class Pred>
int count_if(Iter begin, Iter end, Pred pred){

    int sum = 0;

    for(; begin != end; ++begin){
        if(pred(*begin)) sum++;
    }

    return sum;
}


and than wrote simple predicate function
1
2
3
4
5
template<class T>
bool bigger_than(T val){
    if(10 < val) return true;
    else return false;
}


The problem is that I'm getting this error

/home/girts/Desktop/exercises/chapter_21/exercise_4/main.cpp:40: error: no matching function for call to 'count_if(std::vector<int>::iterator, std::vector<int>::iterator, <unresolved overloaded function type>)'
     std::cout << count_if(vec.begin(), vec.end(), bigger_than) << std::endl;
                                                              ^


If I remove template stuff from my function than its running fine. Also works fine with function object.

Full code if someone wants to run it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* 4. Implement count_if() yourself! Test it !*/

#include <vector>
#include <iostream>

template<class Iter, class Pred>
int count_if(Iter begin, Iter end, Pred pred){

    int sum = 0;

    for(; begin != end; ++begin){
        if(pred(*begin)) sum++;
    }

    return sum;
}

template<class T>
bool bigger_than(T val){
    if(10 < val) return true;
    else return false;
}

struct biger{
    int val;

    biger(int v) : val{v}{}
    bool operator()(int V){
        if(val < V) return true;
        else return false;
    }
};

int main(){

    std::vector<int> vec {8, 12, 9, 5, 33, 4, 5,
                          4, 1, 20, 18, 17, 28, 1};

    //std::cout << count_if(vec.begin(), vec.end(), biger(10)) << std::endl;
    std::cout << count_if(vec.begin(), vec.end(), bigger_than) << std::endl;
}
You forgot to specify what instantiation of bigger_than you want to use.
 
std::cout << count_if(vec.begin(), vec.end(), bigger_than<int>) << std::endl;
Last edited on
Try

std::cout << count_if(vec.begin(), vec.end(), bigger_than<int>) << std::endl;

for line 40.

Andy
Ohh, thanks guys so much :)
Topic archived. No new replies allowed.