Passing function ptr to template function

1
2
3
4
5
6
7
8
9
10
11
12
13
template<typename T>
void templateTest(T **&arr, int n, float (*key)(T)) {
    for(int i = 0; i < n; i++) {
        cout << key(arr[i]) << ", ";
    }
    cout << endl;
}


float ptr_example_key(Example *p1) {
    return p1->getValue();
}

//Main
1
2
3
4
5
6
7
8
9

Example **examples = new Example*[n];
for(int i = 0; i < n; i++) {
      Example *example = construct_random_heap_example();
      examples[i] = example;
}

templateTest(examples, n, ptr_example_key);


error ptr_example_key

error: no matching function for call to 'templateTest(Example**&, int&, float (&)(Example*))'
note: candidate: 'template<class T> void templateTest(T**&, int, float (*)(T))
note: template argument deduction/substitution failed:
note: deduced conflicting types for parameter 'T' ('Example' and 'Example*')

is there something that i missed in code?
Last edited on
Your ptr_example_key takes in an Example* (pointer-to-example), but your template is being deduced as T = Example (i.e. not a pointer).

Try making it float (*key)(T*)
Last edited on
Topic archived. No new replies allowed.