c++ template笔记

2014-11-24 03:26:04 · 作者: · 浏览: 0

1. 数组

template 
  
   
void array_print(T (&arr)[N])
{
	for(int i = 0; i < N; ++i)
	{
		cout << arr[i] << endl;
	}
}
  

int arr[5] = {1, 2, 3, 4, 5};
	array_print(arr); //实例成 array_print(int(&)[5])

2. 返回值

template 
  
   
T1 sum(T2 x, T3 y)
{
	return x.size() + y.size();
}
  

size_t l = sum
  
   (string("xx"), string("yyy"));
  

3. 非类型形参数

template
  
   
int area()
{
	return w * h;
}
  

int a = area<8,6>();

4. 特化

template 
  
   
int compare(const T &v1, const T &v2)
{
	if(v1 < v2) return -1;
	if(v2 < v1) return 1;
	return 0;
}

template <>
int compare
   
    (const char* const &v1, const char* const &v2) { return strcmp(v1, v2); }
   
  

const char *str1 = "hello", *str2 = "world";
	int n1 = 1, n2 = 2;
	compare(str1, str2);
	compare(n1, n2);

5. 缺省模板参数

template 
  
   
class A {
public:
	A() : m_value1(), m_value2()
	{
	}
	~A()
	{

	}
private:
	T1 m_value1;
	T2 m_value2;
};
  

A
  
    aa;
  

6. traits

template 
  
   
class TypeTraits;

template <>
class TypeTraits
   
    { public: typedef int ReturnType; }; template <> class TypeTraits
    
     { public: typedef int ReturnType; }; template <> class TypeTraits
     
      { public: typedef int ReturnType; }; template <> class TypeTraits
      
       { public: typedef double ReturnType; }; template 
       
         typename Traits::ReturnType average(T const* begin, T const* end) { typedef typename Traits::ReturnType ReturnType; ReturnType total = ReturnType(); int count = 0; while (begin != end){ total += * begin; ++begin; ++count; } return total / count; }
       
      
     
    
   
  

char str[] = "i love you";
	cout << average
  
    >(&str[0],&str[10]) << endl; // 看class TypeTraits
   
  

参考文献:

1. < >

2. http://www.cnblogs.com/stephen-liu74/archive/2012/09/12/2639736.html

3. http://www.cppblog.com/youxia/archive/2008/08/30/60443.html