Copy Constructor and Templates

Started by
4 comments, last by Mattijs2 15 years, 6 months ago
I found the following on Wikipedia about the C++ copy constructor : "Contrary to expectations, a template copy constructor is not an explicit copy constructor." (Article link) Is this true? I created the following test program in Visual Studio 2005, and it works fine.

template <typename T, int num_items>
class cTest
{
	public :

		const int	m_num_items ;
		T *		m_items ;

		cTest () : m_num_items (num_items)
		{
			m_items = new T [num_items] ;
		}

		~cTest ()
		{
			delete [] m_items ;
		}

		cTest (const cTest &source) : m_num_items (source.m_num_items)
		{
			m_items = new T [num_items] ;
			for (int k = 0 ; k < m_num_items ; k++)
				m_items [k] = source.m_items [k] ;
		}
} ;



int main (int argc, char *argv [])
{
	cTest<int, 4> t1 ;
	cTest<int, 4> t2 (t1) ;

	return 0 ;
}






Advertisement
What you have is a non-template copy constructor of a template class. What the article is referring to is template copy constructors. Ex:
template <typename U>cTest(const U & something) {  // stuff}
Yes, sorry, that is something different. Is that why the following does not compile?

template <typename T, int num_items>class cTest{	public :		const int	m_num_items ;		T *		m_items ;		cTest () : m_num_items (num_items)		{			m_items = new T [num_items] ;		}		~cTest ()		{			delete [] m_items ;		}		cTest (const T &item) : m_num_items (1)		{			m_items = new T [1] ;			m_items [0] = T ;	// error C2275: 'T' : illegal use of this type as an expression		}} ;int main (int argc, char *argv []){	cTest<int, 1> t1 ;	cTest<int, 1> t2 (12) ;	return 0 ;}
No, that's because you're doing the equivalent of:
int a = int;

You probably mean:
m_items [0] = T();
Yes, I must be sleeping. I meant the following, which works:

template <typename T, int num_items>class cTest{	public :		const int	m_num_items ;		T *		m_items ;		cTest () : m_num_items (num_items)		{			m_items = new T [num_items] ;		}		~cTest ()		{			delete [] m_items ;		}		cTest (const T &item) : m_num_items (1)		{			m_items = new T [1] ;			m_items [0] = item ;				}} ;int main (int argc, char *argv []){	cTest<int, 1> t1 ;	cTest<int, 1> t2 (12) ;	return 0 ;}
I get it now. The thing is that when you have

template <typename T> cTest::cTest <const T &source) { //... }

and you use cTest for T, you get

cTest::cTest <const cTest &source) { //... }

which looks a _lot_ like a copy constructor for cTest, but isn't.


This topic is closed to new replies.

Advertisement