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;
}

二、输出结果


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值