C++模板实战3:模板参数

2014-11-24 07:27:22 · 作者: · 浏览: 0

模板参数可以是class,也可以是:整数及枚举类型、指向对象或函数的指针、对象或函数的引用、对象成员的指针。

1 整数模板参数,但是必须是编译期常量,实例如下:

#include
  
   
#include
   
     using namespace std; template
    
      class array{//具备越界检查的数组 public: T& operator[](unsigned i){ if(i>=size) throw std::out_of_range("array out of arrage\n"); else return elems[i]; } public: T elems[size]; }; int main(){ array
     
       myArray; std::cout<
      
       
2 函数指针作为模板参数,实例如下:

#include
        
         
using namespace std;
template
         
           void fun(T value){ f(value); } template
          
            void show(T value){ cout<
           
            >(string("hello world")); return 0; }
           
          
         
        

3 指针或引用作为模板参数,实例如下:

#include
        
         
using namespace std;
template
         
           class test{ public: void operator()(){ cout<<*p<
          
            class other{ public: void operator()(){ cout<
           
             one; one(); other
            
              two; two(); return 0; }
            
           
          
         
        

4 类成员函数作为模板参数,实例如下:

#include 
        
         

class some_value;

typedef int (some_value::* some_value_mfp)(int);//some_value_mfp代表一类以int为参数以int为返回值的函数,使用:some_value_mfp ptr=&some_value::add_by;//将add_by地址赋值给ptr函数指针,现在调用ptr(int var)就等于调用add_by

template
         
           //func是一个成员函数指针型模板参数 int call(some_value &value, int op) {return (value.*func)(op);} class some_value { int value; public: some_value(int _value) : value(_value) {} int add_by(int op) {return value += op;} int sub_by(int op) {return value -= op;} int mul_by(int op) {return value *= op;} }; int main() { using namespace std; some_value v0(0); cout << call<&some_value::add_by>(v0, 1) << endl; cout << call<&some_value::sub_by>(v0, 2) << endl; cout << call<&some_value::mul_by>(v0, 3) << endl; }
         
        
上面的例子个人觉得在C++11中用std::function/std::bind可以替代,并且更简洁明了。还有模板本身也可以作为模板,这些都有点偏了,可能实际中用的不多。