Let’s suppose that I have a class container:
template<class T, int size>
class container
{
private:
T* data;
int length;
public:
container()
{
data=new T[size];
length=size;
}
~container()
{
if(length>0)
delete[] data;
}
container& operator= (container<T,size> c)
{
if(length>0)
delete[] data;
data=new T[c.length];
length=c.length;
for(int i=0; i<length; i++)
data[i]=c.data[i];
return *this;
}
};
The problem is that if I have two container of different size, I can’t use the = operator to assign one to the other.For example:
container<int,4> c1;
container<int,5> c2;
c1=c2; // syntax error: 4!=5
Classes like c++11 array allow to do this.
How to do that?
Templates are just that — templates the compiler uses to make classes, not classes themselves.
Thus,
container<int,4>andcontainer<int,5>are completely separate classes, with all of the access restrictions that implies.In particular, this means that
container<int, 4>‘s assignment operator cannot access theprivatememebers ofcontainer<int,5>.There are a few ways to get around this:
container‘s public interface.containerclasses of the same type asfriendsby adding the following line to your class:Code:
and declaring your assignment operator as follows: