Friday, November 22, 2013

Categories of template parameters

There are three categories of template parameters, which I mentioned in another post. Here I just want to give a demo to demonstrate their uses all at 
once.

1) Type: that are preceded by the class or typename keywords , 
    which represent types. 
    eg:   class T

2) Non-Type : regular typed parameters, similar to those found in functions.
    eg:    int N

3) Template :  that are preceded by the template keywords
   which represent templates.   
    eg:    template <class U> class V
                     

Example:

// Notice T in red is used to tell what kind of type template U is taking.
// Otherwise, I need to hard-code it as something inside the class. 
// 1) C is type.
// 2) N is non-type parameter,
// 3) U is template
template <class C, int N, class T, template<class anySymbol> class U>
class takeThree
{
public:
        takeThree(C a1, U<T> b1):a(a1), b(b1), size(N) {}
        void print() const { a.print(); cout << "size = " << size <<endl; b.print();cout << endl;}
private:
        C a;
        U<T> b;  
        int size;
};



Test code: 

    anOrdinaryClass a(3);
    aTemplateClass<float> b(3.2);
    takeThree<anOrdinaryClass, 100, float, aTemplateClass> take_three(a, b);
    takeThree<aTemplateClass<float>, 200, float, aTemplateClass> take_three2(b, b);
    take_three.print();
    take_three2.print();

Result: 
ord data is 3
size = 100
temp data is 3.2

temp data is 3.2
size = 200
temp data is 3.2

Support classes listed down here :


class anOrdinaryClass
{
public:
        anOrdinaryClass(int b):a(b){}
        void print() const      {cout << "ord data is " << a <<endl;}
private:       int a;
};

template <class T>
class aTemplateClass
{
public:
        aTemplateClass(T b){a=b;}
        void print() const      {cout << "temp data is " << a <<endl;}
private:        T a;
};

No comments:

Post a Comment