A Complete Guide to Programming in C++ part 76

A Complete Guide to Programming in C++ part 76. This book provides both novice and experienced programmers with a comprehensive resource manual for the C++ programming language. Readers gain experience in all aspects of programming, from elementary language concepts to professional software development, with in depth coverage of all the language elements en route. These elements are carefully ordered to help the reader create useful programs every step of the way. | TEMPLATE PARAMETERS 729 Multiple Template Parameters You can also define templates with multiple parameters like the following class template Example template class U class V class Demo . . . which has two parameters U and V. A class Demo U V is defined for each pair of U V types. A template parameter need not always be a type name. Normal function parameters are also permissible particularly pointers and references. Example template class T int n class Stack . . . This defines the class template Stack T n that is parameterized with the type T and an integer n. The example on the opposite page uses the parameter n to specify the size of an array used to represent a stack. The major advantage is that the number of array elements is already known when an object of the template class is instantiated. Objects can then be created without allocating dynamic storage. This simplifies the definition of the stack template. The copy constructor the assignment operator and the destructor no longer need to be defined Restrictions Two restrictions apply to template parameters other than type parameters they cannot be modified they cannot be floating-point types. The following expression would thus be invalid in the definition opposite Example n Error changing template parameter Even though double type template parameters are not permissible Example template class T double d Error class Demo . . . pointers and references to floating-point types are Example template class T double ref class Demo . . . 730 CHAPTER 32 TEMPLATES TEMPLATE ARGUMENTS Sample program Passing arguments to function templates ------------------------------------------------- include iostream using namespace std template class T T min T x T y return x y x y int main short x 10 y 2 cout x x y y endl cout The smaller value is min x y endl Call is ok. double z1 float z2 cout nThe smaller value is min z1 z2 endl Not ok double z3 cout nz1 z1 z3 z3 endl cout The smaller value is min z1 z3 .

Không thể tạo bản xem trước, hãy bấm tải xuống
TÀI LIỆU MỚI ĐĂNG
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.