决仕~上班族 » 日志 » 05·02 a question about template class in C++
05·02 a question about template class in C++
jazz 发表于 2007-05-02 21:37:31
But in VC++, the template class's declaration and defenition that is often the source code must be in the same file, or else it will not pass compile progress, and the compile error message is external symbols can not be resolved, just like we use a external variant in the function without using external directive for the very variant. I remember this question happened before when I was a undergraduate. But the template function has no such question. Surprised? Maybe.
Below is just a sample, you can try it if you are interested in it:
//stu.h
namespace jazz
{
template<typename Type> class Array
{
public:
Array(int size_);
~Array() throw();
Type& operator[](int index);
void dump();
private:
Type* data;
size_t size;
};
template<typename Type> Array<Type>::Array(int size_) try: size(size_),data(new Type[size_])
{
}catch(std::bad_alloc& e)
{
throw;
}
template<typename Type> Type& Array<Type>::operator [](int index)
{
if(index<0 || index>= size)
throw std::out_of_range("script index is out of range");
return data[index];
}
template<typename Type> Array<Type>::~Array() throw()
{
delete[] data;
}
template<typename Type> void Array<Type>::dump()
{
for(int i=0;i<size;i++)
cout<<data[i]<<endl;
}
}
//there is no error above
------------------------------------------
//stu.h
namespace jazz
{
template<typename Type> class Array
{
public:
Array(int size_);
~Array() throw();
Type& operator[](int index);
void dump();
private:
Type* data;
size_t size;
};
}
//stu.cpp
namespace jazz
{
template<typename Type> Array<Type>::Array(int size_) try: size(size_),data(new Type[size_])
{
}catch(std::bad_alloc& e)
{
throw;
}
template<typename Type> Type& Array<Type>::operator [](int index)
{
if(index<0 || index>= size)
throw std::out_of_range("script index is out of range");
return data[index];
}
template<typename Type> Array<Type>::~Array() throw()
{
delete[] data;
}
template<typename Type> void Array<Type>::dump()
{
for(int i=0;i<size;i++)
cout<<data[i]<<endl;
}
}
//there is compile error above
