template parameter

Hello,

i have following template class
1
2
3
4
  template <int nr = 10>
  class my_class{
  ...
 };

Is there a way to use a variable by the instantiation of an object of my_class instead of an integer number?

So
1
2
int x = 12;
my_class<x> class1;

or
1
2
#define NR 12;
my_class<NR> class1;

instead of
 
my_class<12> class1;


Thanks for the help.
The first case won't work as is. The template parameter has to be known at compile time. So if you change this to const int x = 12; - it will be ok. That's why for example my_class<sizeof(int)> class1; will also work. In C++11 you can make more sophisticated things that can go into template parameters using the constexpr specifier.

Second case will work (remove a semicolon after 12 in your define though) because for the compiler it will be the same as your last one - the preprocessor will substitute NR with 12 before compilation starts.
Last edited on
thank u
Topic archived. No new replies allowed.