Archived

This topic is now archived and is closed to further replies.

Alpha_ProgDes

templating an actual class

Recommended Posts

ok i learned this:
      
template<class ItemType>
class Blah {
.....
}

template<class ItemType>
void Blah<ItemType>::function ( ) {
...
}
  
and you can replace that with int, char, and other simple data types. but how do you template actual classes ? it seems rather complex and i've not gotten very far (getting an algorithm together was perplexing and frustrating). i just don't see how i can just do this:
  StackType<Blah> stackOfClasses;  
and not run into all types of problems. can anyone help PLEASE!!?? it would be much appreciated edit: fixed BIG messed up [edited by - Alpha_ProgDes on December 24, 2002 2:14:34 PM] [edited by - Alpha_ProgDes on December 24, 2002 2:15:29 PM] [edited by - Alpha_ProgDes on December 24, 2002 2:35:32 PM]

Share this post


Link to post
Share on other sites
Use the [ source ] tags to stop the browser messing up the templates.


  
template <class T> class CContainer
{
public:
CTest() {}
~CTest() {}

const T& GetData() {return m_theData;}
void SetData(const T& rData) {m_theData = rData;}

protected:
T m_theData;
};


HTH

Share this post


Link to post
Share on other sites
A class is just like a POD in terms of templating. The compiler just sticks the type in there and tries to compile. You''ll only run into problems if you start assuming stuff about the type, for example if you assume a particular class will have an = operator. This isn''t a bad thing, but a few of the STL algorithms have these kinds of assumptions depending on which one you use. Sometimes you''ll need a parenthesis operator, otherwise it will just shoot a compile error into your face.

I''m a bit concerned about how you''re declaring your templates, though. I don''t see a class or typename anywhere near your template.

Share this post


Link to post
Share on other sites
quote:

If you template a class does all the member functions (whatever else) function properly or do i have to do something extra/special?


Eh? I don''t understand... As Zipster said, all the compiler does is copy and pastes your type in. So if your class returns a T&, and the class is created like this: CContainer<int> test, you''ll get an int& returned. Likewise, if you created it like this: CContainer<CMyBigFunkyClass> AnotherTest, you''d get a CMyBigFunkyClass& returned.



Share this post


Link to post
Share on other sites
quote:
so how then do you get around the operator overloading and such?

If you are writing your own template class, then don''t rely on the templated type to have certain operators defined. However, for libraries such as STL, there might be places where your class type must overload an operator or two. There''s no way around that.

Share this post


Link to post
Share on other sites