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

There is a template function for passing a parameter by reference + callback function, but there is a problem if the parameters are passed by reference to the callback function, and then the compiler generates an error:

There is no corresponding function to call 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 
}
+4
source share
1 answer

The output Tin the second call is not executed because it Toccurs in two derived contexts that output different values T.

In the first parameter T& arg, it Tis displayed on int, because the argument xis of type int.

func_t<T>, T int&, func2 void(int&).

int int& , .

, , T int&:

func<int&>(x, func2); // ok
+6

Source: https://habr.com/ru/post/1654091/


All Articles