Thread: Class Templating

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912

    Class Templating

    I'm making a basic AI program for decoding information, and class templates looks they could be very useful to my source code. Unfortunately, my tutorial doesn't explain how to do it, or even it itself. I was wandering if omseone could either link me to a good tutorial, or explain to me (and the syntax for doing it). Thanks in advance.

    Also: is this just a C++ thing or can C structures do it too?

  2. #2
    Seeking motivation... endo's Avatar
    Join Date
    May 2002
    Posts
    537
    This is a simple class to add things up. They can be anything for which the += operator is defined (or overloaded )

    Code:
    template < class T >
    class Sum
    {
    public:
       Sum( ) { total = 0; }
       Sum( T* typeArray, int size );
       T calcTotal( );
    
    private:
       T* array;   //pointer to array
       T total;   //total
       int size;   //size of array passed via constructor
    };
    
    T Sum::calcTotal( )
    {
       total = 0;
       for( int i = 0; i < size; i++ )
       {
          total += array[ i ];
       }
       return total;
    }
    This may not be the best example,its just a simple explanation of a template class. This now means that any user defined type (or standard C++ type) for which the += operator is defined can be used in this class. Its very useful when dealing with things such as sorting algorithms and data structures.

    If thats not clear ask again and I'll try to explain it better....

  3. #3
    Registered User raimo's Avatar
    Join Date
    Jun 2002
    Posts
    107
    There seems to be a brief explanation:
    http://www.cplusplus.com/doc/tutorial/tut5-1.html

    Templates are not available in standard C. They are a property of C++ which provides some abstraction.

  4. #4
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    Although some of their functionality can be imitated in straight C using macros.

  5. #5
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    Thanks - I got it now

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Specializing class
    By Elysia in forum C++ Programming
    Replies: 6
    Last Post: 09-28-2008, 04:30 AM
  2. matrix class
    By shuo in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2007, 01:03 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM