Tuesday, February 28, 2012

Nontype Template Parameters


Konnichiwa!!

Lately I have been very excited programming and I really have to do an effort to continue chapter after chapter in order not to mess up the blog. However, if you are interested to get further feel free to check out the examples page.

So then, let's work!

First off, what's the meaning of nontype template parameters? Indeed, the idea is so simple, is just to use types like int inside templates. Till now, all template examples we have seen has been with the reserve word typename or class but the powerful of templates don't finish here.

For example, a Matrix:
template<int W, int H>
struct Matrix{
    double m[W][H];
};

Thus, now, we can simply constructor of a Matrix like this:

Matrix<4,4> A={0,0,0,0,
               0,1,0,0,
               0,0,1,0,
               0,0,0,1};
Matrix<4,1> B={1,2,3,4};

In the case using a class in lieu of a struct, we could not do it in this way unless we started using C++11.
Another example usefull with matrices could be the below:

template<int sizeAX,int sizeAY, int sizeBY>
void mult(const Matrix<sizeAX,sizeAY>& A,const Matrix<sizeAY,sizeBY>& B, 
Matrix<sizeAX,sizeBY>& C);
Note: I'm using pass by reference, check out FAQ if dont get it at all why I used &'s or const.

This function multipy does A · B = C
But not always matrices can be multiplied. With the definition we did, we can do A · B but not B · A.
In this case we'll have a compile error:

(I change the variable names to make it more understandable)

void mult(const Matrix<4,1>& A,const Matrix<4,4>& B,
void mult(const Matrix<sizeAX,sizeAY>& A,const Matrix<sizeAY,sizeBY>& B,

                     sizeAX = 4;         sizeAY = 4;
                     sizeAY = 1;         sizeBY = 4;
SizeAY don't match so here is where the error occurs. But, in fact, is better to have this error in compile time than runtime.

Struct Matrix here!!

A similar example, here:

template<typename T, int ROWS, int COLS>
class Matrix;
template<int InCOLS>
Matrix<T, ROWS, InCOLS> operator*(const Matrix<T, COLS, InCOLS>& in) const;
If template COLS of our matrix match with the rows of the supose matrix to be multiply then we are able to do it. And the result of this multiply will be ROWS and InCOLS.

Slowly:

A(3,2)*B(2*10) = C(3,10)

If colsA(2) is equal to rowsB(2).

sizeC = (rowsA, colsB)

2 comments:

  1. Nice topic! Very interesting and well-composed.I just wanted to bring to your attention that Please use which are giving excellent look.Template examples

    ReplyDelete
  2. Thank you! I will take a look.

    ReplyDelete