Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Generic Class Definition

Posted on 1999-07-08
16
Medium Priority
?
268 Views
Last Modified: 2010-04-02
Please give me a simple example (or a very good hyperlink of the same) of how to create a generic class in C++.  By generic, I mean one that the user can instantiate with different data types.  To receive full credit, I would like to see in this example how the user must supply a function that should be overloaded (like the "=" operator) and how items of this unknown data type are used in the generic definition.  I have coded this in Ada95, but have yet to learn how to do it with C++.  

If my question is hard to understand, please leave a comment for me.  

Thanks in advance.
0
Comment
Question by:Laminamia063099
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 8
16 Comments
 
LVL 7

Accepted Solution

by:
KangaRoo earned 180 total points
ID: 1199537
class sole_owner
{
      public:
            explicit sole_owner(T* ptr = 0) : pointer(ptr) {}
      ~sole_owner() { delete pointer; }

            sole_owner& operator=(T* ptr) { adopt(ptr); return *this; }
                        operator T* ( void )      const { return pointer; }
            T*            operator ->      ( void )      const { return pointer; }
            T&       operator *      ( void ) const { return *pointer; }

            bool      operator !      ( void ) const { return (T*)(pointer) == 0; }

            void      adopt       ( T* ptr )      { if (pointer) delete pointer; pointer = ptr; }
            T*            disown ( void )      { T* tmp(pointer); pointer = (T*)(0); return tmp;}
            void      destroy( void )      { adopt((T*)(0)); }

      private:
         T*      pointer;
      private:
            sole_owner(sole_owner& so)                                  { adopt(so.disown()); }
            sole_owner& operator=(sole_owner& s)
      { adopt(s.disown()); return *this; }
};

0
 
LVL 7

Expert Comment

by:KangaRoo
ID: 1199538
In this case, the destructor must be overload (called by delete pointer). This could be made more explicit by replacing
  delete pointer;
with
  pointer->DestroyYourself()
In which case that function has to be provided by the user class
0
 
LVL 3

Author Comment

by:Laminamia063099
ID: 1199539
(Wow, I thought I knew what I was doing, but sometimes I just feel like I'm in over my head.)

So, what you mean, KangaRoo, is that I would inherit from this class to be able to use it's functionality with a specific data type?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Author Comment

by:Laminamia063099
ID: 1199540
Sorry for my ignorance, but what is T?  Where does it come from?
0
 
LVL 7

Expert Comment

by:KangaRoo
ID: 1199541
T is some yet undefined type (or class). It is to be defined by the user, who can then pass it as parameter of the template:

class MyClass {};
sole_owner<MyClass> some_identifier;
Instantiates the template class (generates code for this particular type), and of course an object (named
 some_identifier) of that particular class instance.

You don't need to inherit from this class, although it is possible (not recommended though, why is left as exercise for the reader :)
It is my auto_ptr implementation and used as:

void f()
{
  ...
  sole_owner<SomeResource> resource = new SomeResource;
  ...
  resource->SomeMember();
  ...
} // sole_owner automatically deletes the containe object.
0
 
LVL 3

Author Comment

by:Laminamia063099
ID: 1199542
Thank you for your help.  The points are yours, though I have one more question... What is a template? (as compared to a class).
0
 
LVL 3

Author Comment

by:Laminamia063099
ID: 1199543
How does the class template recognize that the type inside < > replaces T in the template  (or am I way off)

Thanks for your help again.  

The more I learn, the more I realize how little I know.
0
 
LVL 7

Expert Comment

by:KangaRoo
ID: 1199544
A template is just that. Basically it defines a code pattern for classes and functions. Difficult to explain actually. Compared to a common class, it describes the classes that are instantiated from it.

You can also have templates for functions:

template<class T>
T max(const T& t1, const T& t2)
{ return t1 < t2 ? t2 : t1; }
0
 
LVL 7

Expert Comment

by:KangaRoo
ID: 1199545
>> How does the class template recognize that the type inside < > replaces T in the template
Look at it as a typedef. You specify the name of the type in the declaration of the template. like

template<class T> void f(T t)
{
   T temporary;
   ...
}

Within the template, T is considered as a declared class or type. As soon as it is used, eg:
  int i = 5;
  f(i);
it is instantiated for that type:
void f( int t )
{
  int temporary;
  ...
}

You don't have to use T, thats just a convention (short for Type). You can also use more meaningfull names:
template< class Key, class Value > class map;
0
 
LVL 3

Author Comment

by:Laminamia063099
ID: 1199546
Thanks a lot!  It makes perfect sense, and it's not so hard to understand (though I'm sure I'm oblivious to the finer points for a long time to come).  So, you don't have to instantiate it so much, but you can just use it as is (as long as all the operators are defined for the type you use)?  Where it says, template<class T>void f (T t), does it say "class" for anything you plan to instantiate it with, no matter it be a class or a regular data type?  In other words, is class the buzz-word always used in the template definition?  

Thanks again, I owe you one!
0
 
LVL 3

Author Comment

by:Laminamia063099
ID: 1199547
Would this be correct:

template<class T>class MyTemplateClass {
  T * tPtr; //....
}

To instantiate:
class X { int i };
X x;
MyTemplateClass mine(x);  //T is now replaced by type X.
0
 
LVL 7

Expert Comment

by:KangaRoo
ID: 1199548
Use
  MyTemplateClass<int> mine;
to instantiate the template. Note that this will also create an object of class MyTemplateClass<int> (named 'mine'). Iow, you have to specify the type arguments when instantiating template class.

Off course you could pass parameters to a constructor:
template<class T>class MyTemplateClass {
  T * tPtr;
  MyTemplateClass(T*) ;
  //....
} ;


class X { int i };
X* pX = new X;
MyTemplateClass<X> mine(x);
 
 
 
   
 

0
 
LVL 7

Expert Comment

by:KangaRoo
ID: 1199549
>> Where it says, template<class T>void f (T t), does it
>> say "class" for anything you plan to instantiate it
>> with, no matter it be a class or a regular data type?  

Yes, the class keyword within the '<>' can be replaced with the typename keyword, which emphasizes your point
  template<typename T> void f(T t);
which is the same as
  template<class T> void f (T t);
0
 
LVL 3

Author Comment

by:Laminamia063099
ID: 1199550
Thanks again! I'll try to read up more so I don't have to ask so many questions, but I may be back again!

Thanks for answering more than what you got points for, I owe you!
0
 
LVL 7

Expert Comment

by:KangaRoo
ID: 1199551
Your welcome, templates can be quite intimidating at first, but very rewarding to work with.
0
 
LVL 3

Author Comment

by:Laminamia063099
ID: 1199552
I know.  I wrote generic packages in Ada, which is the same thing.  It was about a year ago, and getting started with generic code is, as you say, intimidating!
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question