Syntax of C++ Templates - Comparison

# Syntax of C++ Templates - Comparison

20:31
Wed
16
Sep 2015

I noticed recently how C++ syntax differs when you define a class template, template instantiation, specialization or partial specialization. Here is an example:

// Template class definition.
template<typename T>
class Class1
{
public:
    void Print() { printf("Class1 template\n"); }
};

// Template class instantiation.
template
class Class1<int>;

// Template class specialization.
template<>
class Class1<double>
{
public:
    void Print() { printf("Class1 specialization for double\n"); }
};

// Template class partial specialization.
template<typename T>
class Class1<T*>
{
public:
    void Print() { printf("Class1 partial specialization for pointers\n"); }
};

Having these classes defined, following code fragment:

Class1<int> objInt;
objInt.Print();
Class1<double> objDouble;
objDouble.Print();
Class1<int*> objPointer;
objPointer.Print();

Produces following output:

Class1 template
Class1 specialization for double
Class1 partial specialization for pointers

Here is how the syntax can be compared:

Comments | #c++ Share

Comments

STAT NO AD
[Stat] [STAT NO AD] [Download] [Dropbox] [pub] [Mirror]
Copyright © 2004-2017