Difficulty:
Problem:
Why does the code below fail to be compiled?
StructT
{
Operator
STD: string ()Const
{
Return
STD: string ();
}
Operator
Int()Const
{
Return
Int();
}
};
Int
Main ()
{
T;
Int
I = T;
STD: String S = T;
I = T; // success
S = T; // failed
}
Answer:
Because the standard library does not provideBool Operator= (Const
STD: string &, const STD: string &);
Template<TypenameChart,Typename
Traits,TypenameAlloc>
Bool
Operator= (ConstSTD: basic_string <chart, traits, alloc> &,ConstSTD: basic_string <chart,
Traits, alloc> &);
When S = T for comparison, the compiler can use the first parameter S to export the three template parameters, namely chart, traits, and alloc, and then use t to derive them, the result cannot be deduced because t is not basic_string <>. What is the role of the operator STD: string () const Conversion Function in T? In fact, this conversion function is not used here. c ++ does not provide a rule to convert the function before deriving the function template parameters. To solve this problem, let the compiler explicitly convert t to STD: string before deriving the type of the second parameter.
S = STD: string (t );
At this point, some people may wonder that basic_string does not provide basic_string (const
STD: string &) constructor.
Template<TypenameChart,Typename
Traits,TypenameAlloc>
Basic_string (ConstBasic_string <chart, traits, alloc> &);
According to the above statement, how does the explicit conversion of STD: string (t) Complete the derivation of function template parameters? In fact, STD: string is not a class template, but is converted into a basic_string <char> template class by instance. STD: string (t) is not deduced because the chart has been clarified, traits,
Alloc template parameters, so the operator STD: string () const takes effect.