c++ template笔记

时间:2022-01-09 23:38:16

1. 数组

template <typename T, int N>
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 <class T1, class T2, class T3>
T1 sum(T2 x, T3 y)
{
return x.size() + y.size();
}
size_t l = sum<size_t>(string("xx"), string("yyy"));

3. 非类型形参数

template<int w, int h>
int area()
{
return w * h;
}
int a = area<8,6>();

4. 特化

template <typename T>
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 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 <typename T1, typename T2 = bool>
class A {
public:
A() : m_value1(), m_value2()
{
}
~A()
{ }
private:
T1 m_value1;
T2 m_value2;
};
A<int> aa;

6. traits

template <typename T>
class TypeTraits; template <>
class TypeTraits<char>{
public:
typedef int ReturnType;
}; template <>
class TypeTraits<short>{
public:
typedef int ReturnType;
}; template <>
class TypeTraits<int>{
public:
typedef int ReturnType;
}; template <>
class TypeTraits<float>{
public:
typedef double ReturnType;
}; template <typename T,typename Traits>
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<char,TypeTraits<char> >(&str[0],&str[10]) << endl; // 看class TypeTraits<char>

参考文献:

1. <<C++ Primer>>

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