I'm unable to use char* or string in Vector class.
I know what the problem is but unable to find a proper answer.
One solution is like I can call explicit intialization for char* or string
and perform operations for only those but unable to get how to do that.
Can someone help please.
I want Vector to work with any datatype.
I know what the problem is but unable to find a proper answer.
One solution is like I can call explicit intialization for char* or string
and perform operations for only those but unable to get how to do that.
Can someone help please.
I want Vector to work with any datatype.
Code:
template<class T>
class Vector
{
int _size;
T* data;
char* charData;
public:
Vector(int size = 0):_size(size),data(new T[_size])
{}
~Vector()
{
delete[] data;
}
friend istream& operator>>(istream& is, Vector<T>& v)
{
for(int i=0; i<v._size; ++i)
{
is>>v.data[i];
}
return is;
}
T& operator[](int index);
const T& operator[](int index)const;
};
template<class T>
T& Vector<T>::operator[](int index)
{
return data[index];
}
template<class T>
const T& Vector<T>::operator[](int index)const
{
return data[index];
}
int main()
{
//class Vector works for int, char, double
//but fails for string or char*
Vector<int> v(5);
cin>>v;
for(int i=0; i<5; ++i)
cout<<v[i]<<"\t";
Vector<char* > v(5); //fails for this or string
cin>>v;
for(int i=0; i<5; ++i)
cout<<v[i]<<"\t";
return 0;
}
Comment