template<class T>
struct S {
static int const N = 1;
};
extern template class S<int>;
template<class T>
int f(T n) {
return n + S<T>::N; // line 10
}
int main() {
return f(1); // line 14
}
//template class S<int>; // intentionally commented out to trigger error
我得到:
foo.cpp: In function ‘int f(T) [with T = int]’:
foo.cpp:10: instantiated from ‘const int S<int>::N’
foo.cpp:10: instantiated from ‘int f(T) [with T = int]’
foo.cpp:14: instantiated from here
foo.cpp:10: error: explicit instantiation of ‘S<int>::N’ but no definition available
但爲什麼我得到的錯誤?
- 做一個明確的模板實例聲明的一點是,這樣的定義可以別處,然而編譯(不鏈接)給出了一個錯誤。 (在實際應用中,當前註釋過的外部實例化聲明將在另一個翻譯單元中)。
- 在這種情況下,該值具有常量初始化程序因此編譯器理論上可以直接使用該值。
- 當我不做顯式模板實例化聲明時,我(奇怪)不必明確定義
S<T>::N
。
這是在Mac OS X 10.6.6上的g ++ 4.2.1。
那麼你可以使用`enum {N = 1};`而不是`static const`。 – kennytm 2011-02-17 18:02:33
@KennyTM:不回答問題。很顯然,這個例子是我的真實代碼的簡化例子。真正的代碼需要一個無符號長設置爲〜0,AFAIK,枚舉不能是「無符號」。 – 2011-02-17 18:05:05