zoukankan      html  css  js  c++  java
  • c++ template笔记

    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

  • 相关阅读:
    结果偏见 (行为经济学)
    天下没有免费的午餐
    双环学习
    信息对称、网络效应
    为什么说盲维是认知升级的重要概念?
    给思维找一个支点
    风险是一种商品
    认知方法论第一课
    A*算法深入
    A*算法入门
  • 原文地址:https://www.cnblogs.com/fuhaots2009/p/3478807.html
Copyright © 2011-2022 走看看