c++泛型示例

一个粗糙的c++范型示例

#include <iostream>
#include <fstream>
#include <sys/stat.h>
#include <vector>

using namespace std;

class CacheDataA
{
public:
    int aValue;
};

class CacheDataB
{
public:
    int bValue1;
    int bValue2;
};

template <class T>
class BaseCacheEngin
{
public:
    BaseCacheEngin(int maxCacheCount);
    std::vector<T *> cacheDataList;
    int cacheData(T *cacheData);
    T *popData();

private:
    int mMaxCacheCount;
};

template <class T>
BaseCacheEngin<T>::BaseCacheEngin(int maxCacheCount)
{
    mMaxCacheCount = maxCacheCount;
}

template <class T>
int BaseCacheEngin<T>::cacheData(T *cacheData)
{
    cacheDataList.push_back(cacheData);
    if(cacheDataList.size()>mMaxCacheCount){
        cacheDataList.erase(cacheDataList.end());
    }
    return 0;
}

template <class T>
T *BaseCacheEngin<T>::popData()
{
    if (cacheDataList.empty())
    {
        return NULL;
    }
    return cacheDataList.front();
}

int main()
{
    cout << "hello world!\n";

    BaseCacheEngin<CacheDataA> *cacheEnginA = new BaseCacheEngin<CacheDataA>(3);
    BaseCacheEngin<CacheDataB> *cacheEnginB = new BaseCacheEngin<CacheDataB>(5);

    CacheDataA *a1 = new CacheDataA();
    CacheDataA *a2 = new CacheDataA();
    CacheDataA *a3 = new CacheDataA();
    CacheDataA *a4 = new CacheDataA();
    a1->aValue = 1;
    a2->aValue = 2;
    a3->aValue = 3;
    a4->aValue = 4;
    int result = cacheEnginA->cacheData(a1);
    result = cacheEnginA->cacheData(a2);
    result = cacheEnginA->cacheData(a3);
    result = cacheEnginA->cacheData(a4);
    cout << "cacheData result:" << result << "\n";

    CacheDataB *b = new CacheDataB();
    b->bValue1 = 1;
    b->bValue2 = 3;
    result = cacheEnginB->cacheData(b);
    cout << "cacheData b result:" << result << "\n";

    CacheDataA *aTemp = (CacheDataA *)cacheEnginA->popData();
    cout << "pop Cache data A, value:" << aTemp->aValue << "\n";

    CacheDataB *bTemp = (CacheDataB *)cacheEnginB->popData();
    cout << "pop Cache data B, value1:" << bTemp->bValue1 << "\n";

    /**
     * With Templete limit, this code will cause build error:
     * cannot convert ‘CacheDataB*’ to ‘CacheDataA*’
     */
    // cacheEnginA->cacheData(b);

    cout << "Bye!\n";
    return 0;
}