Non-Type parameters for templates [duplicate]
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.
精彩评论