特例化模板

原创
2015/04/21 15:25
阅读数 117

c++允许我们对模板进行特例化,当对特殊的类型进行模板化时,一般性已经不满足我们的应用了。

考虑一个例子:

template<class T>

class Stack

{

 .....
};

特例化模板分为两种:

(1)一种是对整个类进行特例化

例如:

#include<string>

template<>

class Stack<std::string>

{

.....;
};

使用这种方法需要对整个类的成员函数进行编写:

在定义函数时使用以下方式

template<>

type Stack<std::string>::funcname(...)

{
}

 

(2)还有一个就是对类中的个别成员函数进行特例化

这种方法只需要在定义成员函数的时候进行例外的编写,形式如下:

template<>

type Stack<int>::funcname(...)

{
}

 

下面附上完整的源代码例子:

//////////////////////////////////////////

////Stack.h file

#include<deque>
#include<string>
#include<stdexcept>

////////////////////
//一般的模板类 
template<class T>
class Stack
{
public:
    void pop();
    T Top();
    void push(const T& value);
    bool Empty()
    {
        return (de.size()==0);
    }
private:
    std::deque<T> de;
};

///////////////////////////////
//全部特例化类模板 
template<>
class Stack<std::string>
{
    public:
    void pop();
    std::string Top();
    void push(const std::string& value);
    bool Empty()
    {
        return (de.size()==0);
    }
private:
    std::deque<std::string> de;
};

//////////////////////////////
///一般模板的实现 
template<class T>
void Stack<T>::pop()
{
    if( Empty() )
    {
        throw std::out_of_range("堆栈中为空");
    }
    de.pop_back();
}

template<class T>
void Stack<T>::push(const T& value)
{
    de.push_back(value);
}

//局部特例化 
template<>
void Stack<int>::push(const int & value)
{
    de.push_back(value);
}

template<class T>
T Stack<T>::Top()
{
    if( Empty() )
    {
        throw std::out_of_range("堆栈中为空");
    }
    T value=de.back();
    return value;
}
//////////////////////////////////////////////
///一般的模板实现完毕
 
//////////////////////////////////////////
//特殊的模板实现
void Stack<std::string>::pop()
{
    if( Empty() )
    {
        throw std::out_of_range("堆栈中为空");
    }
    de.pop_back();
}

void Stack<std::string>::push(const std::string& value)
{
    de.push_back(value);
}

std::string Stack<std::string>::Top()
{
    if( Empty() )
    {
        throw std::out_of_range("堆栈中为空");
    }
    std::string value=de.back();
    return value;

 

////////////////////////////////////////////////////////////////

////main.cpp

#include <cstdlib>
#include <iostream>
#include "Stack.h"

using namespace std;

int main(int argc, char *argv[])
{
    try
    {
        Stack<int> intstack;
        Stack<string> stringstack;
        intstack.push(10);
        cout<<intstack.Top()<<endl;
        intstack.pop();
    
        stringstack.push("helle world");
        cout<<stringstack.Top()<<endl;
        stringstack.pop();
    }catch(exception error)
    {
        cout<<error.what()<<endl;
    }
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

 

 

如果想要对他函数的的调用进行详细的了解,只需要设置相应的断点并调试。


展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部