Thread: Template class parameter

  1. #1
    Registered User
    Join Date
    May 2006

    Template class parameter

    Hello everyone,

    Sometimes a template class is defined to have only parameter and no type (e.g. class something) information. Like the below sample. My question is, why define template class in this way (e.g. I can implement in an alternative way to put the parameter into constructor)? If there is no type information (e.g. class something), there will be no benefits and reasons to use the template class. Any comments?

    #include <vector>
    #include <iostream>
    using namespace std;
    template <int size> class Foo {
    	int limit;
    		limit = size;
    int main (int argc, char** argv)
    	Foo <100> f1; // limit member of instance f1 is 100
    	Foo <200> f2; // limit member of instance f2 is 200
    	return 0;

    thanks in advance,

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Portland, OR
    It allows you to specialize the template based on particular values, and it enables metaprogramming tricks. For instance imagine you had a mathematical vector class called vector<N> where N is the number of dimensions. You might specialize these classes to give them intuitive constructors to supply initial values. For instance:

    vector<1> vec1(1.0);
    vector<3> vec2(0.0, 1.0, -3.0);
    The 1-dimensional constructor has 1 argument, and the 3-dimensional constructor has 3 arguments. There is no way to do this without specializing on the integral template parameter.

  3. #3
    The larch
    Join Date
    May 2006
    As one thing it provides a mean to declare automatic arrays in a class and let the user choose the size of the class:
    template <int max>
    class A
        int array[max];
    In this case max has to be a compile-time constant and template arguments is the way to pass it to the class. It also allows you to create different instances of the same class that use an array with a different size.

    One curious thing is that you can use the template argument throughout the class as a constant, and you don't need to store it as a member (limit in your code).
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing Functor as template parameter
    By MarkZWEERS in forum C++ Programming
    Replies: 6
    Last Post: 11-09-2008, 09:13 AM
  2. linker error
    By tasha302 in forum C++ Programming
    Replies: 3
    Last Post: 12-14-2006, 12:00 AM
  3. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  4. Prime Number Generator... Help !?!!
    By Halo in forum C++ Programming
    Replies: 9
    Last Post: 10-20-2003, 07:26 PM