What is a template and how can I use one?

This is a discussion on What is a template and how can I use one? within the C++ Programming forums, part of the General Programming Boards category; Anyone have a simple example of what a template is and how it's used?...

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    155

    What is a template and how can I use one?

    Anyone have a simple example of what a template is and how it's used?

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,702
    Their just great generic programming tools.

    Code:
    template <typename number>
    number add( number a, number b){
      return a + b;
     }
    
    template <class type>
    class List {
    //...
    };
    
    
    int main(){
     int a = 15, b = 16;
     float x = 15.3, y = 16.1;
    
     printf("%i", add(a, b));
     printf("%.2f", add(x, y));
    
     List <int> list;
     list.push_back(10);
     list.push_back(12);
     
     //...etc...
     return 0;
    }
    Code:
    bool flip(bool value)
    {
        return std::pow(std::exp(1), std::complex<float>(0, 1) 
        * std::complex<float>(std::atan(1)*(1 << (value + 2))))
        .real() < 0;
    }

  3. #3
    Registered User
    Join Date
    Oct 2002
    Posts
    155
    ... wha---?!

  4. #4
    Registered User
    Join Date
    Oct 2002
    Posts
    155
    ...

  5. #5
    TransparentMember correlcj's Avatar
    Join Date
    Jun 2002
    Posts
    378

    Hope this helps!

    Originally posted by Nakeerb
    ...
    answer I personally dont know if there is a simple example myself but this will get you more acainted with them.
    Hope this helps!
    cj
    "Be formless, shapeless, like water... You put water into a cup, it becomes the cup, you put water into a bottle, it becomes the bottle, you put it in a teapot, it becomes the teapot... Now water can flow, or it can crash, be water my friend."
    -Bruce Lee

  6. #6
    Registered User
    Join Date
    Oct 2002
    Posts
    155
    I do not understand

  7. #7
    TransparentMember correlcj's Avatar
    Join Date
    Jun 2002
    Posts
    378

    ...

    Originally posted by Nakeerb
    I do not understand
    what is it you dont understand? Read the answer and try some examples.

    "Be formless, shapeless, like water... You put water into a cup, it becomes the cup, you put water into a bottle, it becomes the bottle, you put it in a teapot, it becomes the teapot... Now water can flow, or it can crash, be water my friend."
    -Bruce Lee

  8. #8
    Registered User
    Join Date
    Apr 2002
    Posts
    26
    Look at my example below:


    PHP Code:
    #include <iostream.h>

    template <class T>
     
    T sum (T xT y){
    T resulty;
    return 
    result;
    }

    int main()
    {

    cout<<"The sum of two float numbers, 1.264 and 5.984 is: "<<sum(5.984,1.264)<<endl
        
    <<"The sum of two integers, 5 and 6 is: "<<sum(5,6)<<endl
        
    <<"the sum of two characters, A and B is: "<< sum('A','B')<<endl
        
    <<"the sum of two doubles, 564654646 and 5454873333 is: "<< sum(564654646,5454873333);
        
    system("PAUSE");

        return 
    0;

    I hope that helped...

  9. #9
    ...
    ... is offline
    Registered User
    Join Date
    Feb 2002
    Posts
    465
    did someone call me?
    I came up with a cool phrase to put down here, but i forgot it...

  10. #10
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    A few people have tried to show you templates but have done little in explaining them.
    When you write a template you are in effect giving your compiler instructions for generating code. You write 1 template function or 1 template class and your compiler will generate as many different versions of these functions as are needed.
    Lets look at template functions first.
    Imagine a function to return the max of two ints. Something simple like this...
    Code:
    int max (int num1,int num2)
    {
          if (num1>num2) return num1;
          else // not necessary but i believe makes code more readable
          return num2;
    }
    Now immediately we can see that this function could be made more generic. In fact we could make this function work for any type that supports operator > (). To allow for sizeable objects we will change the passing from value to const reference and we will template it on a single generic type T. Like this...
    Code:
    template < typename T >
    const T& max (const T& num1, const T& num2)
    {
          if (num1 > num2) return num1;
          else
          return num2;
    }
    Now whenever we call max() the compiler will either generate the correct function or will complain that the type we are trying to find max of doesnt support operator > (). Before templates you either had to write ugly #define macros or had to write each specific function yourself. Templates give the convenience of macros with the type-safety of writing your own function for each type.
    While on the subject of template functions we should talk about explicit specialization. For instance the max of 2 char* strings should use strcmp() and not operator > (). So with this in mind we write a specialized version of max.
    Code:
    const char* max (const char* str1,const char* str2)
    {
         if (strcmp(str1,str2) < 0) return str1;
         else
         return str2;
    }
    Your compiler will always look for a specialization before generating code from your template. That is garaunteed by the c++ standard.

    Sorry dinners ready now. short essay on template classes and specialization and partial specialization may follow after dinner.

    If so far you are still failing to understand this then point out exactly what you are not following and we will try to elaborate a bit.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21