Cfon Cfon - 1 year ago 105
C++ Question

C++11: function template: passing parameters by reference

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) {

void func1(int arg) { }
void func2(int& arg) { } //<-- (1)

int main() {
int x = 0;
func(x, func1);
func(x, func2); //<-- (2) compilation error

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download