Function templates
I am prompted to create a function template that will take 4 arguments:
- pointer
- link
- pointer to array
- function pointer
How do you accomplish this task? I've tried:
#include <iostream>
using namespace std;
int nothing(int a)
{
return a;
}
template<typename T> T func(int *L, int &M, char *K, int (*P)(int))
{
cout << L << "," << M << "," << K[0] << "," << P() << endl;
return 0;
}
int main()
{
int x = 3;
int *z = &x;
int &y = x;
char c[3];
int (*pf)(int) = nothing;
cout << "some result of func" << func(z, y, c, pf) << endl;
system("pause");
return 0;
}
This gives me "no suitable function, I think, for" pf ". Also now I have no control over what to pass to pf, or am I wrong?
a source to share
You're almost there. However, in C ++ reference is referred to as &
(not $
), a pointer to the array is a pointer to its first element, and the function pointer extra parentheses are needed: T (*pf)()
.
Note that it is called a function template (as opposed to class templates).
Edit : (You shouldn't have to edit your question for the answers asked so far to suddenly become meaningless.)
pf(x)
calls the function stored in pf
. pf
is already a function pointer, so pass it as is.
(Also, your declaration P
has an accept function, X
but an pf
accept function int
. I assume this is an edit error?)
Note that with function pointers there are types 1..N, one result type and argument types 0..N. "Create a function template that accepts a function pointer" can mean any of these. Or does it mean
template< typename F >
void f(F func);
which can be called using any function pointer.
a source to share
Now you have problems ...
TYPE (*P)(x)
says you expect a function pointer to take a type argument x
- change it to an existing type.
In an expression, func(z, y, c, pf(x))
you are trying to call a function pointer pf
instead of just passing it.
Then you call func
with parameters based on different types for the first 3 parameters, int
and char
, but func
expects them to be based on the same type.
Try to write down what types func
will be called, and try to compare it with the signature for func
the replacement TYPE
to say The int
.
eg. if you have the following:
template<typename T> void f(T* a, T* b);
and try calling it like this:
int* a = 0;
int* b = 0;
f(a, b);
the compiler instantiates and calls the function
void f<int>(int*, int*);
But if you do the following:
int* a = 0;
char* b = 0;
f(a, b);
what should be called?
void f<int> (int*, int* ); // doesn't match, 2nd argument is char*
void f<char>(char*, char*); // doesn't match, 1st argument is int*
a source to share