练习16.1
::实例化就是模板通过实际调用而确定类型及其运算,抽象到具体
练习16.2
template <typename T> int compare(const T& v1,const T& v2) { if(v1<v2)return -1; if(v2<v1)return 1; return 0; } #include <iostream> int main () { std::cout<<compare(2,3)<<std::endl; }
练习16.3
[Error] no match for 'operator<' (operand types are 'const Sales_data' and 'const Sales_data')
练习16.4
template <typename T,typename N> T find(const T& v1,const T& v2,const N&q) { for(auto d=v1;d!=v2;++d) { if(*d==q) return d; } return v2; } #include <vector> #include <iostream> int main () { std::vector<int> a{1,2,3,5,6,7,8,9}; std::cout<<*find(a.begin(),a.end(),7)<<std::endl; }
练习16.5
template <typename T,unsigned n> void print (const T(&a)[n]) { for(unsigned i=0;i!=n;++i) { std::cout<<a[i]<<std::endl; } } #include <vector> int main () { int a[10]={1,2,3,5,6,7,8,9}; print(a); }
练习16.6
template <typename T,unsigned n> T* begin ( T(&a)[n]) { return &a[0]; }
练习16.7
template <typename T,unsigned n> constexpr unsigned size( T(&a)[n]) { return n; }
练习16.8
::因为很多时候没有定义<运算符,但是肯定定义了等于运算符
练习16.9
::函数模板就是通用的功能函数板子,可以套各种你想要的类型,类模板也是类似
练习16.10
::会生成一个类的代码
练习16.11
加一个friend class ListItem<elemType>;
练习16.13
::同类型函数友元
练习16.14
template <std::string::size_type height,std::string::size_type width> class Screen{ //友元 friend class Window_mgr; public: //类型成员 typedef std::string::size_type pos; //构造函数 Screen():cursor(0),contents(height*width,' '){} Screen(char c):cursor(0),contents(height*width,c){} //类成员函数 char get() const {return contents[cursor];}; inline char get(pos hit,pos wit)const; Screen &move(pos r,pos c); void some_member ()const; Screen &set (char); Screen &set(pos,pos,char); Screen &display(std::ostream &os){do_display(os);return *this;} const Screen &display(std::ostream &os) const {do_display(os);return *this;} pos size()const{return height*width;} private: //类成员 pos cursor=0;//光标 std::string contents; mutable size_t access_ctr;//追踪每个成员函数被调用次数 void do_display(std::ostream &os)const{os<<contents;} }; template <std::string::size_type height,std::string::size_type width> inline Screen<height,width>& Screen<height,width>::move(pos r, pos c) { pos row = r * width; cursor = row + c; return *this; } #endif
标签:std,const,14,Screen,练习,pos,16.1,return,primer From: https://www.cnblogs.com/yddl/p/16607305.html