Chaos in C ++: Conversion Function

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.