jeudi 13 mars 2014

Step-by-step through C++ Template

As some of my teammate always complain that template-based code are really hard to understand and that they would prefer coding without, I will try here to explain how it works and propose some complexity-growing example.

NOTE1: that post will be periodically update....
NOTE2: that post/tutorial is design in a way to can do all exercise without local compiler, I wrote a solution using Ideone, so create your account and write your own solution for all exercise.

A first look at the template syntax <> and their usage:

We using template and/or writing template you "can" meet the < CONTENT > syntax
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.

1st Example

Imagine we want a function to multiply by 2 an integer

int mulByTwo(int v) { return v*2;}

And we can write int I = mulByTwo(2);

Now we also want mulByTwo but for float and we avoid code duplication.
Question: Write only one function MulByTwo to deal with:

int I = mulByTwo(2);
double D = mulByTwo(2.0);

Solution: here

Observe basic/simple "type deduction" error message

Now using the 1st example, what's happen if you call:
string S = mulByTwo("blahblah....");

Now build a function Sum, range-based to deal with iterator and pointer of any kind !

Tips: an iterator is just a simple base class implementing some operator like: ++,--,+=,-=,*, ->, [], etc...

Add the end with only 1 function, you should be able to execute:

int main() {
    int testArray[5] = {0,1,2,3,4};
    vector v = {0, 1, 2, 3, 4};
    vector s = {"hello", " ", "world"};
  
    cout << Sum(v.begin(), v.end()), cout << endl;
    cout << Sum(testArray, testArray + sizeof(testArray)/sizeof(testArray[0])), cout << endl;
    cout << Sum(s.begin(), s.end()), cout << endl;
  
    return 0;
}


Solution: here

How to use integral template

as for type deduction, the compiler will prepare everything at the compilation time.

Example: template&ltint&gt struct example { static double value = N * 2.0; }
If we write: cout << example&lt5&gt::value;

Exercise: Use that to compute factoriel&lt5&gt at compile time
Solution: here.

------ > followings section are under construction <------------------------ br="">

Solving ambiguity / Explicit Template Arg Specification

 

Default template  argument


Template and Specialization




Aucun commentaire :

Enregistrer un commentaire