Thinking in C++ 2nd edition Volume 2 Standard Libraries & Advanced Topics revision 1 phần 3

Al Stevens Góp phần biên tập, bác sĩ Dobbs Tạp chí "Eckel của cuốn sách là một trong những chỉ như vậy rõ ràng giải thích làm thế nào để suy nghĩ lại về xây dựng chương trình định hướng đối tượng. Cuốn sách cũng là một hướng dẫn tuyệt vời trên các ins and outs của C + + là một tiền thưởng thêm. " | 3 Templates in depth Nontype template arguments Here is a random number generator class that always produces a unique number and overloads operator to produce a familiar function-call syntax C03 Unique random number generator ifndef URAND_H define URAND_H include cstdlib include ctime template int upperBound class Urand int used upperBound bool recycle public Urand bool recycle false int operator The generator function template int upperBound Urand upperBound Urand bool recyc recycle recyc memset used 0 upperBound sizeof int srand time 0 Seed random number generator template int upperBound 121 int Urand upperBound operator if memchr used 0 upperBound if recycle memset used 0 sizeof used sizeof int else return -1 No more spaces left int newval while used newval rand upperBound Until unique value is found used newval Set flag return newval . . endif URAND_H The uniqueness of Urand is produced by keeping a map of all the numbers possible in the random space the upper bound is set with the template argument and marking each one off as it s used. The optional constructor argument allows you to reuse the numbers once they re all used up. Notice that this implementation is optimized for speed by allocating the entire map regardless of how many numbers you re going to need. If you want to optimize for size you can change the underlying implementation so it allocates storage for the map dynamically and puts the random numbers themselves in the map rather than flags. Notice that this change in implementation will not affect any client code. Default template arguments The typename keyword Consider the following C03 Using typename to say it s a type and not something other than a type template class T class X Without typename you should get an error typename T id re- public void f Chapter 15 Multiple Inheritance 122 class Y public class id public void g int main Y y X Y xy The template definition assumes that the class T that you hand it must .

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
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.