這是一個很好的問題,因爲它很難證明。我們可以利用C++標準中的其他規則來顯示匿名名稱空間中的變量可以具有外部鏈接。
在帶有外部鏈接的int *上進行模板化將會成功,而對具有內部鏈接的int *進行模板化將失敗。
#include <iostream>
namespace {
// not externally linked, won't compile
// const int i = 5;
// external linkage, compiles
extern int i;
int i = 5;
}
template<int* int_ptr>
struct temp_on_extern_linked_int {
temp_on_extern_linked_int() {
std::cout << *int_ptr << std::endl;
}
};
int main() {
temp_on_extern_linked_int<&i>();
}
如程序編譯和運行所示。
$ g++-4.8 main.cpp -o main
$ ./main
5
取消註釋i
的其他定義會導致編譯失敗。
$ g++-4.8 main.cpp -o main
main.cpp: In function 'int main()':
main.cpp:17:30: error: '& {anonymous}::i' is not a valid template argument of
type 'int*' because '{anonymous}::i' does not have external linkage
temp_on_extern_linked_int<&i>();
^
該編譯器相當有幫助。它明確指出,因爲i
沒有外部鏈接,編譯失敗。
i
的註釋定義具有內部鏈接,因爲它是不受外部限制的const。 (§3.4.6)特技的
Variables at namespace scope that are declared const and not extern have internal linkage.
部分未編譯爲C++ 11。
Why did C++03 require template parameters to have external linkage?
我懷疑腳註可能是C++ 03中的一個剩餘部分,其中未命名名稱空間中的名稱具有外部鏈接(因爲否則它們不能用作模板參數)。作者只是忘記刪除它。 – 2014-09-25 01:00:46