Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template functor cannot deduce reference type

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?

like image 632
maciekp Avatar asked Dec 04 '22 13:12

maciekp


2 Answers

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
}
like image 185
UncleBens Avatar answered Dec 23 '22 11:12

UncleBens


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.

like image 32
Charles Beattie Avatar answered Dec 23 '22 12:12

Charles Beattie