A not-so-quick question about templates!

Started by
1 comment, last by Obolus 22 years, 9 months ago
Hi all, I''m back with problem no. 2 : I have a class which stores a pointer to a templated object. I want the normal class to set its pointer to point to any instance of that template, e.g.: template class TemplatedClass { ... private: T m_SomeData; ... }; class NormalClass { private: ... TemplatedClass< T > * m_Link; ... public: ... void SetData( TemplatedClass< T > * NewLink ) { m_Link = NewLink; } ... }; So, I create a TemplatedClass with, say, an ''int'' as the data type. The problem occurs when I try to set the pointer in the NormalClass to point to a specific TemplatedClass object, e.g.: NormalClass normal; TemplatedClass< int > *templated = new TemplatedClass< int >; normal.SetData( templated ); VC++ produces an error at the "normal.SetData( templated );" line, saying: error C2664: ''SetHead'' : cannot convert parameter 1 from ''class TemplatedClass< int > *'' to ''class TemplatedClass< T > *'' So it seems to me that you can''t pass templated objects as member function parameters. Is there a solution to this problem, or was I simply over-estimating the usefulness of a template? Thanks again, Gareth
Advertisement
I find templates confusing but try this solution.

  template<T>void SetData(TemplatedClass<T> * NewLink)...  
The ''T'' means absolutely nothing to the compiler inside the ''NormalClass'' definition. It is looking for a class literally named T, which doesn''t exist. NormalClass needs to be templatized on class T (although it doesn''t have to be called T, it can be anything) as well so that the member m_Link and the parameter NewLink know what type they will point at.

(PS: Please don''t post the same question in 2 threads...)

This topic is closed to new replies.

Advertisement