开发者

Non-Type parameters for templates [duplicate]

开发者 https://www.devze.com 2023-02-01 03:29 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: What does template <unsig开发者_如何学Pythonned int N> mean?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

What does template <unsig开发者_如何学Pythonned 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 ;  
}


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消