Pointers to functions problem

I was reading a tutorial on this site about pointers to functions, and I wanted to create something on my own.

I wanted to make a simple function that adds two numbers, and then prints it out via another function; but for some reason it's not working. I'm using Xcode, and I get an error message saying "No matching function for call to 'sum'".

Help appreciated!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

template <class type>
void print(type a) {
    cout << a << endl;
}

template <class type>
void sum(type a, type b, type (*function)(type)) {
    (*function)(a+b);
}

int main() {
    int i1=1, i2=3;
    float f1=1.4, f2=14.9;
    
    sum(i1, i2, print); // This is where I get the error message.
    
    return 0;
}
First of all you wrote type (*function)(type)

This means that the function passed needs to have the same return type as 'type'. You might want to change this to 'void' if you want your print function to be able to be passed.

Second of all, you are passing a pointer to a function, so in when you pass 'print' as the argument you need to get it's pointer address:

sum(i1, i2, &print);

See if this helps.
You have the type wrong. Your print functions returns void, not type.
Last edited on
Ah, that makes sense. Changing type (*function)(type) to void (*function)(type) did the trick!

Thanks to both of you!
Topic archived. No new replies allowed.