cvs.gedasymbols.org/archives/browse.cgi   search  
Mail Archives: djgpp/1997/06/12/02:20:17

From: Darren Grant <darn AT xl DOT ca>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Templates
Date: Sat, 07 Jun 1997 14:59:31 -0700
Organization: loners anonymous
Lines: 88
Message-ID: <3399D9C3.2DB0@xl.ca>
References: <3 DOT 0 DOT 16 DOT 19970608164854 DOT 2e3f02e6 AT hem1 DOT passagen DOT se>
Reply-To: darn AT xl DOT ca
NNTP-Posting-Host: c17.xl.ca
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Peter Palotas wrote:
> 
> I have been wondering for quite some time what templates are. I have seen
> in some headerfiles in STL (I think) something like Class foo<t> and now I
> am wondering what this is. I would be very grateful if someone could tell
> me where I could read about this stuff, or just tell me what it is and how
> it can be used.


Templates provide a way of passing datatypes as parameters in C++. 
Consider the simple function sum() below, that takes two ints as
parameters and returns their sum:

   int sum(int x, int y)
   {
      return x+y;
   }


Using a template to generalize this function to handle any class with +
and copy-constructor functionality:

   template <class T>
   T better_sum(T x, T y)
   {
      return x+y;
   }


This template function is called like a regular function, except that it
can take any single datatype (class) T for both parameters, providing
that +/copy functionality exists for T.  Please note that in-built c
datatypes have such functionality (float, int, unsigned, char, etc.),
but classes must either inherit it, or provide new operator+() and
copy-constructor definitions.

example:

     #include <iostream.h>
     #include <_string.h>

     template <class T> T better_sum(T, T);
     void main();


     template <class T> T better_sum(T x, T y)
     {
        return x+y;
     }

     void main()
     {
        float a, b = 1.0, c = 1.0;
        a = better_sum(b, c);
        cout << a << endl;

        int d, e = 1, f = 1;
        d = better_sum(e, f);
        cout << d << endl;

        String g, h = "hel", i = "lo";
        g = better_sum(h, i);
        cout << g << endl;
     }



Template classes (not functions) are utilized a little differently, but
with the same idea of automatically accounting for many different
datatypes.  To create an instance of a class decclared thus,

   template <class T> class Foo
   {
       .
       .
       .
   };

requires provision of a datatype parameter list.  i.e.

   Foo<float>  a;
   Foo<int>    a;
   Foo<String> a;
   etc.


The functionality required of class T is determined by the
implementation of Foo<class T>.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019