Reputation: 245
There is a kind of template function to pass a parameter by reference + callback function, but there is a problem if the parameters are passed by reference to callback function then compiler is throwing an error:
no matching function for call to
func(int&, void (&)(int&))
.
What's wrong?
template<typename T>
using func_t = void(T);
template<typename T>
void func(T& arg, func_t<T> callback) {
callback(arg);
}
void func1(int arg) { }
void func2(int& arg) { } //<-- (1)
int main() {
int x = 0;
func(x, func1);
func(x, func2); //<-- (2) compilation error
}
Upvotes: 4
Views: 159
Reputation: 119174
Deduction of T
in the second call fails because T
occurs in two deduced contexts which deduce different values of T
.
In the first parameter, T& arg
, T
is deduced to int
since the argument x
has type int
.
In the second parameter, func_t<T>
, T
is deduced to int&
since the argument func2
has type void(int&)
.
Since the two deduced types, int
and int&
, differ for the same parameter, deduction fails.
However, you can do the right thing by explicitly specifying that T
should be int&
:
func<int&>(x, func2); // ok
Upvotes: 6