Solmyr's essay Series II: ambiguous traps

Source: Internet
Author: User

"Why ?!", Zero muttered while drinking water, and looked at the code on the front display with hate. "Why is there a compilation error for such a simple call ...... "

"This is because your design is too poor !"

Success! Zero was shocked by solmyr, which appeared in the back of the ghost, and almost all of the water was sprayed out.

"Cough! Cough! S ...... Solmyr, when are you standing behind me ?", Zero struggled to calm down his cough and tried to recall whether solmyr had caught the handle.

Solmyr grabbed a chair and sat down: "I was there when you started to do something silly. It was this bad design that caused your compilation errors ."

"Where ...... Where ?"

"Here ." Solmyr grabbed the keyboard and marked the following code:

Void somefunc (int I)
............

Void somefunc (float F)
............

Int main ()
{
............
Somefunc (1.2); // error! Ambiguous call
............
}

"I am wondering, too." zero, as always, scratched its head and tried to compress the wisdom that doesn't exist. "This simple function overload should be very clear. When I call it here, it clearly shows a floating point number. Obviously, we should call somefunc of the float version. The most strange thing is that without this call, the entire program compilation connection is completely normal. It can be seen that this overload function is legal ."

"Well, yes, it is indeed legal, but it does not mean it is legal. Zero. Read this section and read the article "50 commandments" by the Prophet Meyers. (Note: it refers to the book "Objective C ++ 2/E) in Clause 26, how to describe C ++'s philosophy of 'ambiguity. ", Solmyr opened a book and pointed to several lines.

"C ++ ......"

"Stand up and read aloud !"

Zero stood up and said, "C ++ also has a philosophical belief that the potential ambiguity is not a mistake ."

The seat next to it was uploaded with a low smile. People in the distance looked at it and cast curious eyes. Zero suddenly felt like a dumb. When zero saw solmyr's fake smile, he realized that he was designed again by solmyr.

"Well, after understanding this, we can further discuss it." solmyr started to turn into the subject. "Do you remember what I said above 1.2 last time ?"

Zero shows the expression of memories: "Well ...... 1.2 is a constant written in the code '...... It should be a double type constant ."

"This is the problem: when the compiler sees the request for calling a function, it will look for the function in your overload function that can match the parameter given in this call request, the result shows that no function parameter is of the double type, so type conversion is required. However, the double type can be converted to either an int or a float type. Which of the following statements can be converted? The compiler does not know, so an error is reported. Do you understand ?"

Zero nodded.

"Then I ask you, will this result in an error during reload compilation ?", Solmyr slightly changed the zero code:

Void somefunc (int I)
............

Void somefunc (double dB)
............

Int main ()
{
............
Float F = 1.2;
Somefunc (f );
............
}

Zero looked at it and learned solmyr's tone: "The Compiler finds that no function parameter is of the float type, so type conversion is required, but the float type can be converted to int, it can also be converted to double. Which one is better? The compiler does not know, so an error is reported ."

"Error !", Solmyr successfully presses the run button, and the program runs normally. The output shows that the double-version somefunc function is called.

Zero is confused again: "Why is it true to select type conversion? What is wrong with the previous one? What is the logic in the middle ?"

"What's important is this sentence: 'which one is better? The compiler does not know '. Didn't you notice that I used an accent on the 'ha' word when I said this sentence ?"

"Have you used stress ?"

"…… This is not the focus. The point is that the compiler can select the float to int and float to double conversions, because float to int will lose data-the like compiler will give a warning when doing this type conversion-while float to double will not lose data, therefore, the compiler knows which one to convert '. In the past, the conversion from double to int to float all required data loss. Therefore, the compiler does not know which one to convert. It cannot make a decision -- "solmyr looked at zero, ask again, "Do you understand?"

Zero frowned and scratched his head. Obviously, it was a little difficult to digest so much information that suddenly appeared: "I think I understand that the key is whether the compiler can differentiate two types of conversions. The key to differentiation here is whether data loss occurs during type conversion ...... So as long as I use the double type in all scenarios where floating point numbers are used, there will be no problem, even if others use float to call it ."

"Correct. However, the problem of ambiguity may not only occur on floating point numbers, for example, such two overloaded functions ...... ", Solmyr, and then type:

Void somefunc (double dB)
Void somefunc (char ch)

"What will happen if I call an integer variable ?", Solmyr turned to zero.

"Er ...... The compiler cannot distinguish between int, double, and int to Char Types. Therefore, an error is returned ."

"Correct. Can you give me several examples ?", Solmyr handed the keyboard back.

Obviously, zero is immersed in meditation. After a while, several lines of code appear on the screen:

// An error occurs when int is used.
Void fun (char ch)
Void fun (int * PI) // or other pointers

// An error occurs when you use int to call the API.
Void fun (double dB)
Void fun (int * PI) // or other pointers

"Well, good. However, you still missed an important situation, "solmyr added," that is, when the parameter has a default value :"

// An error occurs if no parameter is specified during the call.
Void fun (INT I = 10)
Void fun ()

"Day !", Zero seems to be about to crash. "There are so many ambiguous traps. How do I publish my functions? Write in the document: Will the following 153 calling methods cause compilation errors ?"

"Don't be so nervous," solmyr said, "the ambiguity of overloaded functions is not unavoidable. There are two solutions: one is to use templates instead of overloading, in particular, int and double processing algorithms like your somefunc are the same. Second, if you want to use heavy loads, try to ensure that the number of function parameters is different."

"But what if the processing algorithm is different and the number of parameters required by the function is the same ?"

"It's easy to add 'useless parameters', like this :"

Void somefunc (float dB, INT)
Void somefunc (int I)

"The second parameter of the first function does not have any function, so you just need to declare that you have this int parameter. This parameter can be written as follows: this parameter is reserved for future upgrades. Please enter a value of 0 during calls ."

"…… This is probably the case in your documents ...... Ah! It hurts! This is another book !", Zero was hit by a sudden solmyr attack and sent a miserable grief.

"You have to thank Scott Meyers, The precognition. His 50 commandments are light and thin. What I have in my hand is a Bible written by the instructor Bjarne stroustrup (note: the book the C ++ programing language 3/E. Bjarne stroustrup is the designer of the C ++ language. ", Solmyr has once again put on the disguise of self-cultivation, but there is still a trace of arrogance in words ......

"Really cruel guy ......", Zero whispered.

"What are you talking about ?", Once again, we are getting angry.

"No, no! I didn't say anything !", Zero quickly denies and tries to shift the topic. "Ah! I understand and want to avoid ambiguity. One is to replace overload with templates, and the other is to add 'useless parameters' to ensure that the number of parameters of the overloaded function is different. In this way, we can avoid ambiguity, isn't it, teacher solmyr ?". Zero worked very hard to pretend to be innocent.

"…… Poor acting ...... ", Solmyr. "Incomplete, the above method can only solve the function overload. Ambiguity involves a wide range of situations, such as the example in the 50 commandments :"

Class B; // pre-declaration

Class
{
Public:
A (const B &); // A can be constructed based on B
};

Class B
{
Public:
Operator A () const; // B can be converted to
};

"There is no problem with these two classes, but if a function requires the object of a as a parameter, It is a B object in the past :"

Void F (const &)
B;
F (B); // error! Ambiguous call

"Have you noticed the problem? There are two good methods to complete the conversion. One is to use the constructor of A to construct a new class A object with the parameter of B, instead, B is called to convert B to a Class A object. The compiler once again cannot tell which conversion is better and only reports an error. There is also an example of multi-inheritance. You can see it for yourself"

"This ...... This ......", Zero's self-confidence in avoiding traps has just been built up.

"It is impossible to avoid all ambiguous questions," solmyr stood up. "The key is to understand why it happened and how it is easy to induce it, and then handle it with caution, this is true for many problems in C ++. The slate of the 50 commandments is for you. Study it well. Hahahaha !", Solmyr left zero with a smile. It looks like a tall man who is far away ......

"What! It's just a cool-looking guy ...... !", Zero voice is not lost, And a folder is broken through the air and the zero face is in the middle.

"Woo ~ I didn't say anything ~", Zero is powerless to identify the white, but in exchange for the next seat again sent a low smile. Zero understands that today's image is completely ruined ......

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.