作者ric2k1 (Ric)
看板EE_DSnP
标题[情报] HW# 6-1: 关於 template function
时间Tue Nov 27 23:28:51 2007
有人在问为什麽以下程式 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
1F:推 Knossos:我懂了!原来Constant不是常数是变数啊!Orz... 11/27 23:56
※ 编辑: ric2k1 来自: 140.112.21.241 (11/28 10:42)