看板 EE_DSnP 關於我們 聯絡資訊
有人在問為什麼以下程式 compile 不過? ==================================== #include <iostream> using namespace std; template<class T, unsigned arrSize> void insertSort() {} int main() { unsigned s; cin >> s; const unsigned ss = s; insertSort<int ,ss>(); } ==================================== cp37.cpp: In function `int main()': cp37.cpp:14: error: `ss' cannot appear in a constant-expression cp37.cpp:14: error: template argument 2 is invalid cp37.cpp:14: error: no matching function for call to `insertSort()' ==================================== 原因是 template function 會在 compile time 時將 template arguments 帶入, 展開成一段獨立的程式碼, 比方說, insertSort<int, 24> 以及 insertSort<char, 8> 會由此 template function instantiate 出兩份不同的 functions 出來, 分別 compile. 因此, template arguments 必須是在 compile time 就能夠決定的 constant or type, 而不能是 runtime 時才決定的 變數. [觀念] const unsigned ss = s; 此 "const" 乃是用來 "修飾" unsigned ss, 表示他是一個不能被更改的 "變數", 他仍然是存在 stack memory 中的一個 "不能變 (read-only) 的 變數". 他不是 "常數 (constant)" <== 否則他為什麼是在 runtime 才決定值呢? 常數乃是在 compile time 就決定值的東西, 比方說宣告一個 global variable, const int aa = 3; int main() { ... } 此 aa 就不能在 runtime 被決定或修改, 因此他符合常數的條件而能夠用在 insertSort<int, aa>(); -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.121.128.94
Knossos:我懂了!原來Constant不是常數是變數啊!Orz... 11/27 23:56
※ 編輯: ric2k1 來自: 140.112.21.241 (11/28 10:42)