1. 程式人生 > >Linux C/C++ 模板:類模板成員特化

Linux C/C++ 模板:類模板成員特化

一、程式碼

        不需要完全特化整個類,只特化相關函式即可。

#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

//主模板
template <typename T>
class Heap
{
public:
        void push(const T& val);
        T pop();
        bool empty() const { return m_vec.empty(); }

private:
        vector<T> m_vec;
};

template <typename T>
void Heap<T>::push(const T& val)
{
        m_vec.push_back(val);
        push_heap(m_vec.begin(), m_vec.end());
}

template <typename T>
T Heap<T>::pop()
{
        pop_heap(m_vec.begin(), m_vec.end());

        T tmp = m_vec.back();

        m_vec.pop_back();

        return tmp;
}

//
bool strLess(const char* a, const char* b)
{
        return strcmp(a, b) < 0;
}

//類模板成員特化
template <>
void Heap<const char*>::push(const char* const & val) //引數格式必須與原型一致
{
        m_vec.push_back(val);
        push_heap(m_vec.begin(), m_vec.end(), strLess);

}

//類模板成員特化
template <>
const char* Heap<const char*>::pop()
{
        pop_heap(m_vec.begin(), m_vec.end());

        const char* tmp = m_vec.back();

        m_vec.pop_back();

        return tmp;

}

//
int main(int argc, char*argv[])
{
        //
        Heap<int> h1;

        h1.push(1);
        h1.push(3);
        h1.push(2);

        cout<<"is empty: "<<h1.empty()<<endl;
        cout<<h1.pop()<<endl;
        cout<<h1.pop()<<endl;
        cout<<h1.pop()<<endl;
        cout<<"is empty: "<<h1.empty()<<endl<<endl;

        //
        Heap<const char*> h2;

        h2.push("aa");
        h2.push("cc");
        h2.push("bb");

        cout<<"is empty: "<<h2.empty()<<endl;
        cout<<h2.pop()<<endl;
        cout<<h2.pop()<<endl;
        cout<<h2.pop()<<endl;
        cout<<"is empty: "<<h2.empty()<<endl;

        return 0;
}

二、輸出結果