區別在於,使用模板時,值是在編譯時決定和修正的;即編譯程序時。在編譯完成後,你不能改變它們,它們永遠被認爲是常量。
所以,用:
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'語句中使用它。 –