区别在于,使用模板时,值是在编译时决定和修正的;即编译程序时。在编译完成后,你不能改变它们,它们永远被认为是常量。
所以,用:
template<int argument>
void myMethod(){//Do something with *argument* };
如果你打电话myMethod<5>()
,那么argument
值始终是5,功能几乎没有在运行时的任何参数。现在,如果您调用myMethod<6>()
,编译器将重新创建相同的函数,但使用另一个常量值。所以你在运行时会有2个函数。另一方面,使用普通方法,可以在运行时更改它们,即在程序运行时更改它们。再次调用该函数将只执行具有不同参数值的相同代码。
实施例:
template <int L>
void DoSomething()
{
int a[L]; //this works fine here! Becasue L is just a constant that is resolved at compile-time
for(int i = 0; i < L; i++)
{
//do stuff
}
}
void DoSomething(int L)
{
int a[L]; //this won't work, because L is a variable that can be set while the program is running
for(int i = 0; i < L; i++)
{
//do stuff
}
}
模板参数是编译时间常数。例如,当'argument'是一个模板时,你可以在'std :: array'语句中使用它。 –