1

Possible Duplicate:
What does template <unsigned int N> mean?

Hi ! Are non-type template parameters and constants same ? Do the following code work because template parameter cannot be modified ? If can be modified, the compiler should have thrown error while declaring array "a[T]". Is my understanding correct ?

template < int T > 
void foo() {  
  int a[T] ;  
}  

int main( int argc, const char* argv[] ) {  
  foo <3> () ;  
  system("pause") ;  
  return 0 ;  
}
Community
  • 1
  • 1
Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • @ybungalobill Thanks for editing the code part.The way I did was - started with
     tag and ended with 
    . And for each end of line, I have given 1 space. While in preview, it shows correctly. But after posting, it is changing? It would be helpful for further posts if you can say me the way you edited ?
    – Mahesh Dec 27 '10 at 21:08
  • @marcog The link was very helpful. Thanks. – Mahesh Dec 27 '10 at 21:08
  • @marcog: I agree. Especially Johannes' answer is very exhaustive. – sbi Dec 27 '10 at 21:08
  • 1
    You can see it [here](http://stackoverflow.com/revisions/35794e13-1e4d-45f4-9206-71505d9aa94d/view-source). You begin each line of the code with 4 spaces, or just use the code button on the toolbar: {} – Yakov Galka Dec 27 '10 at 21:11

2 Answers2

6

Yeah, kind of. Thing is every time you instantiate a template the compiler will generate specific code for that specific type parametrization. So for instance, in your example if you have foo<3> and foo<5> the compiler will generate code for two separate functions one where T=3 and one where T=5

So yeah, it works because T can't change, the mechanism why it works is slightly more complex though...

Dr G
  • 3,987
  • 2
  • 19
  • 25
2

Yes, non-template parameters have to be constant expressions.

Edward Strange
  • 40,307
  • 7
  • 73
  • 125