Home
Fractals
Tutorials
Books
My blog
My LinkedIn Profile

BOOKS i'm reading

Napoleon Hill Keys to Success: The 17 Principles of Personal Achievement, Napoleon Hill, ISBN: 978-0452272811
The 4-Hour Workweek: Escape 9-5, Live Anywhere, and Join the New Rich (Expanded and Updated), Timothy Ferriss, ISBN: 978-0307465351
The Fountainhead, Ayn Rand, ISBN: 0452273331
Web Hosting Canada

mailto:olivier@olivierlanglois.net

Using integral constant template parameters

08/26/07

Permalink 08:39:43 pm, by lano1106, 327 words, 5879 views   English (CA)
Categories: C++

Using integral constant template parameters

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);
...

Comments, Pingbacks:

Comment from: Emil [Visitor] Email
Very cool :)
PermalinkPermalink 08/27/07 @ 03:04

This post has 4 feedbacks awaiting moderation...

Comments are closed for this post.

Olivier Langlois's blog

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.

April 2024
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        

Search

Custom Search

Misc

XML Feeds

What is RSS?

Who's Online?

  • Guest Users: 1

powered by
b2evolution