I wrote the following code in vs2010:
#include <iostream>#include <typeinfo>using namespace std;template<typename T>void function(const T& value){ cout<<typeid(value).name()<<endl;}class CT{public: friend void function(int iValue);};int main(){ function(0);}
Then, when compiling, I am prompted that the link is incorrect, which means that the function definition cannot be found. However, according to the C ++ standard, the template <t> function () should be called here ().
1. If the friend function in the class is not declared outside, it is invisible outside the class. That is to say, the friend function in the CT is invisible outside the class. Naturally, the function call in main cannot be bound to the friend in CT.
Function. 2. There is a peripheral template <t> function. This means that the function call in main can be successfully interpreted through parameter deduction. In addition, I changed the code to the following, and the output results in vs2010 are even more strange.
#include <iostream>#include <typeinfo>using namespace std;template<typename T>void function(const T& value){ cout<<typeid(value).name()<<endl;}class CT{public: friend void function(int iValue){ cout<<"friend int CT called!"<<endl; }};int main(){ function(0);}
According to vs theory, the friend function in CT should be called, that is, the friend in CT called should be output !, However, in fact, the output is int, which indicates that vs also calls the template <t>
Function, there is a problem here. Since vs also calls the template <t> function, why does it give a link error prompt? Change the code to the following:
# Include <iostream> # include <typeinfo> using namespace STD; Template <typename T> void function (const T & Value) {cout <typeid (value ). name () <Endl;} void function (INT ivalue); // make the friend function in CT visible to the outside class CT {public: Friend void function (INT ivalue) {cout <"friend int CT called! "<Endl ;}; int main () {function (0 );}
At this point, the output will be friend in CT called, which proves that the theory in (1) is true.
To sum up, this is a bug in vs2010 C ++ compiler. (The code in xcode 4.3.2 of Mac OS can be compiled successfully .)