# 模板特化疑问

2015/05/22 12:56

最近在学习模板，对模板特化做了一些实验

下面是代码

``````#include <iostream>
using namespace std;

#include <string>

template <typename T>
class zVector
{
public:
/**
* @brief zVector
* @param size
*/
zVector(int size = 10):m_size(size),p(new T[size]) {}
~zVector(){
delete p;
}
/**
* @brief operator []
* @param index
* @return
*/
T& operator[](int index)  const {
return p[index];
}
private:
int m_size;
T *p;
};

template <>
class zVector<void*>
{
public:
zVector(int size = 10):m_size(size),p(new void*[size]) {}
~zVector(){
delete p;
}
void*& operator[](int index)  const {
return p[index];
}
private:
int m_size;
void* *p;
};

//typedef zVector<void*> zvVector;

template<typename T>
class zVector<T*> : public zVector<void*>
{
public:
T*& operator [](int index) const {
return (T*&)zVector<void*>::operator [](index);
}

};

//template<typename T>
//class zVector<T*> : public zvVector
//{
//public:
//    T*& operator [](int index) const {
//        return (T*&)zvVector::operator [](index);
//    }

//};

int main()
{
zVector<int*> intv;
zVector<double*> doublev;
int i = 1;
double j = 2.11;
intv[0] = &i;
cout << *intv[0] << endl;
doublev[0] = &j;
cout << *doublev[0];
return 0;
}``````

``````#include <iostream>
using namespace std;

#include <string>

template <typename T>
class zVector
{
public:
/**
* @brief zVector
* @param size
*/
zVector(int size = 10):m_size(size),p(new T[size]) {}
~zVector(){
delete p;
}
/**
* @brief operator []
* @param index
* @return
*/
T& operator[](int index)  const {
return p[index];
}
private:
int m_size;
T *p;
};

//template <>
//class zVector<void*>
//{
//public:
//    zVector(int size = 10):m_size(size),p(new void*[size]) {}
//    ~zVector(){
//        delete p;
//    }
//   void*& operator[](int index)  const {
//        return p[index];
//    }
//private:
//    int m_size;
//    void* *p;
//};

typedef zVector<void*> zvVector;

//template<typename T>
//class zVector<T*> : public zVector<void*>
//{
//public:
//    T*& operator [](int index) const {
//        return (T*&)zVector<void*>::operator [](index);
//    }

//};

template<typename T>
class zVector<T*> : public zvVector
{
public:
T*& operator [](int index) const {
return (T*&)zvVector::operator [](index);
}

};

int main()
{
zVector<int*> intv;
zVector<double*> doublev;
int i = 1;
double j = 2.11;
intv[0] = &i;
cout << *intv[0] << endl;
doublev[0] = &j;
cout << *doublev[0];
return 0;
}``````

typedef zVector<void*> zvVector;

cannot call member function 'T*& zVector<T*>::operator[](int) const [with T = void]' without object

0
0 收藏

0 评论
0 收藏
0