I've got a functor f, which takes a function func and a parameter t of the same type as func. I cannot pass g to f because of compilation error (no matching function for call to f(int&, void (&)(int&))
). If g would take non-reference parameter g(int s), compilation finishes. Or if I manually specify template parameter f<int&>(i, g)
, compilation also finishes.
template<typename T>
void f(T t, void (*func)(T)) {}
void g(int& s) {}
int main(int, char*[])
{
int i = 7;
f(i, g); // compilation error here
return 0;
}
How can I get deduction to work?
You can invoke the function like this:
f<int&>(i, g);
But now i will be passed by reference too.
In general, I'd make the function a template type too:
template <typename T, typename F>
void f(T t, F func)
{
func(t); //e.g
}
I think you need either:
void f(T t, void (*func)(T&)) {}
or:
void g(int s) {}
but I prefer:
template<typename T, typename T2>
void f(T t, T2 func) {}
as this will work with functions and functors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With