Highlighting Reference Types in Template Functions

Do I have to explicitly indicate the type of the function template when it comes to deriving a reference type. If so, where is the ambiguity? Let me compare the following 2 code snippets:

1st: link for code

template <typename T> 
void foo(T& var, void(*func)(T&)) // T must be instantiated with int and it does .
{
 ++var;
} 
void ret(int & var){}
int main()
{int k =7; 
foo(k, &ret);
cout<<k;//prints 8
}

Now let's remove both the foo () declaration and we have an error.

2nd: link for code

template <typename T> 
void foo(T var, void(*func)(T)) // T must be instantiated with int& but it doesn't.
{
 ++var;
} 

void ret(int & var){}

int main()
{int k =7; 

foo(k, &ret); //error: no matching function for call to 'foo(int&, void (*)(int&))'
cout<<k;
}

However, if I call foo, explicitly creating an instance with <int&>" foo<int&>(k,&ret);", the code gives the same result as the first. What is the reason for this error? Where is the ambiguity?

Thanks.

+3
source share
2 answers

Fionn answer, , T, int int &. 18.8.2.4/2 :

P A, P A. P/A, . - P/A , , - , .

, , , . , - . , , , enable, , , .. .

+3

:

, , .

, , , - .

, , , pass by value:

void Incr1(int &value) { value++; }
void Incr2(int value) { value++ } //Completely useless but for demonstration

//Now the calling of both functions
int x = 1;
Incr1(x);
Incr2(x);

, , , , int.

#include <iostream>

template <typename T> 
void foo(T var, void(*func)(T))
{
    ++(*var);
} 

void ret(int *var){}

int main()
{
    int k =7; 

    foo(&k, &ret); 
    std::cout<<k;
}

, :

, - T & T.

, :

template <typename T> 
void foo(T var, void(*func)(T&))
{
 ++var;
} 

void ret(int & var){}

int main()
{
    int k =7; 

    foo(k, &ret);
    std::cout<<k;
}
+1

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


All Articles