Sunday, October 09, 2011

An Idiot's Guide to C++ Templates - Part 1

Prolusion

Most of the C++ programmers stay away from the C++ templates, due to its perplexed nature. The excuses against templates:

    Hard to learn
    Compiler errors are vague
    Not worth the effort

Granted that templates are slightly hard to learn, understand and adapt. Nevertheless, the advantages we gain from using templates would outweigh the negatives. There is lot more than generic functions or classes, that can be wrapped around templates. I would explicate them.

While C++ templates and STL (Standard Template Library) are siblings, technically. In this article, I would only cover templates at the core level. Next part of this series would cover more advanced and intersting stuff regarding templates, and some understanding about STL.

Table of Contents:

  • Class Templates
    • Multiple Types with Class Templates

    The Syntax Drama

    As you probably know, template largely uses the angle brackets: The less than ( < ) and the greater than symbol ( > ). For templates, they are always used together in this form:

     < Content >

    Where Content can be:

        class T / typename T
        A data type, which maps to T
        An integral specification
        An integral constant/pointer/reference which maps to specification mentioned above.

    In this part, I would only cover points 1 and 2. The symbol T is nothing but a data-type, which can be any data-type.

    Let's jump to an example. Suppose you write a function that prints double (twice) of a number:

    void PrintTwice(int data)
    {
        cout << "Twice is: " << data * 2 << endl;        
    }

    Which can be called passing an int:

    PrintTwice(120); // 240

    Read more: Codeproject
    QR: template1.aspx

    Posted via email from Jasper-Net