One usage of them commonly demonstrated in C++ Templates textbooks such as C++ Templates is when you want to control the maximum capacity of a container like this:
template< typename T, int MAXSIZE > class stack { ... private: T m_array[MAXSIZE]; };
I have found another very useful property of integral constant template parameters. You can define a class template with an integral constant template parameter and not use it at all in the declaration:
template<int i> class Unique { public: static int var; }; template<int i> int Unique<i>::var;
The property of this template is that a distinct var variable will be created for each instantiation of the template:
Unique<1234>::var = 1; Unique<0>::var = 2;
and so on. By itself, it is more or less useful but imagine that you are dealing with a function registering a callback function that does not let you provide a parameter that will be passed to the callback function but your callback needs to access variables and you must provide more than 1 callback function and each of them needs to access its own set of variables. You could do it by hand by writing x different callbacks and create x sets of variables with different names but by doing that, you would be polluting your namespace and that would be a very long task for nothing. Instead, a class template with an integral constant parameter is the right tool for this situation:
template<int i> class CB { public: static void SetCBParams(int x1, int x2) { m_x1 = x1; m_x2 = x2; } static void CBFunc(); private: static int m_x1; static int m_x2; }; template<int i> int CB<i>::m_x1; template<int i> int CB<i>::m_x2;
and then
CB<1>::SetParam(1,2); registerCB(&CB<1>::CBFunc); CB<2>::SetParam(3,4); registerCB(&CB<2>::CBFunc); ...
This post has 4 feedbacks awaiting moderation...
Comments are closed for this post.
I want you to find in this blog informations about C++ programming that I had a hard time to find in the first place on the web.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
<< < | > >> | |||||
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |