Linux C/C++ 模板:主模板、完全特化
2015-04-11 00:19
267 查看
一、代码
二、输出结果
第1个主模板、第2个完全特化输出结果正确。
第3个结果不正确,因为没有局部特化(针对指针类型的特化)。
#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; } //完全特化 template <> class Heap<const char*> { public: void push(const char* val); const char* pop(); bool empty() { return m_vec.empty(); } private: vector<const char*> m_vec; }; bool strLess(const char* a, const char* b) { return strcmp(a, b) < 0; } void Heap<const char*>::push(const char* val) { m_vec.push_back(val); push_heap(m_vec.begin(), m_vec.end(), strLess); } 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<<endl; // Heap<char*> h3; h3.push("aa"); h3.push("bb"); h3.push("cc"); cout<<"is empty: "<<h3.empty()<<endl; cout<<h3.pop()<<endl; cout<<h3.pop()<<endl; cout<<h3.pop()<<endl; cout<<"is empty: "<<h3.empty()<<endl; return 0; }
二、输出结果
第1个主模板、第2个完全特化输出结果正确。
第3个结果不正确,因为没有局部特化(针对指针类型的特化)。
相关文章推荐
- Linux C/C++ 模板:主模板、完全特化、局部特化
- Linux C/C++ 模板:类模板成员特化
- Step By Step(C++模板重载和特化)
- C++ 中模板的特化 与 偏特化
- 用汇编的眼光看c++(之模板函数) ,(之缺省模板、特化模板) .
- C++模板的特化
- 【C++模板】特化与偏特化 template [partial] specialization
- C++模板:究竟什么是特化?
- 模板完全特化,函数重载的重载,类模板的继承
- Step By Step(C++模板重载和特化)
- 模板完全特化和部分特化
- C++利用不完全实例化来获得函数模板参数的返回值和参数
- C++ 模板的偏特化
- C++ 模板的特化与偏特化
- C++模板的 主版本模板类、全特化、偏特化
- [C++基础]034_C++模板编程里的主版本模板类、全特化、偏特化(C++ Type Traits)
- C++模板中type_traits(类型特化)
- C++模板的特化
- C++模板知识->特化
- 【c++】模板的特化