tailieunhanh - C++ for Mathematicians An Introduction for Students and Professionals phần 6

Người ta có thể nghĩ đến một mẫu như là một lược đồ thủ tục. Khi C + + trình biên dịch gặp max_of_three trong một chương trình, nó sử dụng các mẫu để tạo ra phiên bản thích hợp. Ví dụ, đây là một chính sử dụng tính chất thích nghi của max_of_three. | Polynomials 237 One may think of a template as a procedure schema. When the C compiler encounters max_of_three in a program it uses the template to create the appropriate version. For example here is a main that utilizes the adaptable nature of max_of_three. include include iostream using namespace std int main double x double y double z long long long a b c 14 17 0 cout The max of x y z is max_of_three x y z endl cout The max of a b c is max_of_three a b c endl return 0 The first invocation of max_of_three has three double arguments the compiler uses the max_of_three template with T equal to double to create the appropriate code. The second invocation has three long arguments and as before the compiler uses the template to create the appropriate version of the procedure. The output of this main is as we expect. i The max of is The max of 14 17 0 is 17 k__J The max_of_three template works for any type T for which is defined. If is not defined for the type the compiler generates an error message. For example consider the following main. include iostream include complex include using namespace std int main complex double x 3 0 complex double y -2 3 complex double z 1 1 cout The max of x y max_of_three x y z endl return 0 z is 238 C for Mathematicians When we attempt to compile this program we get the following error messages your computer might produce different error messages . f-------------------------------------------------------------------------X In function T max_of_three T T T with T std complex double 12 instantiated from here 6 error no match for std complex double std complex double operator 7 error no match for std complex double std complex double operator 10 error no match for std complex double std complex double .

TỪ KHÓA LIÊN QUAN