编译器不需要知道编译时的值,&a
就像它需要函数地址的值一样。
可以这样想:编译器会将您的函数模板&a
作为参数实例化并生成“目标代码”(以它用于传递给链接器的任何格式)。目标代码看起来像(它不会,但你明白了):
func f__<funky_mangled_name_to_say_this_is_f_for_&a>__:
reg0 <- /* linker, pls put &std::cout here */
reg1 <- /* hey linker, stuff &a in there ok? */
call std::basic_stream::operator<<(int*) /* linker, fun addr please? */
[...]
如果你实例化f<b&>
,假设b
是另一个全局静态,编译器会做同样的事情:
func f__<funky_mangled_name_to_say_this_is_f_for_&b>__:
reg0 <- /* linker, pls put &std::cout here */
reg1 <- /* hey linker, stuff &b in there ok? */
call std::basic_stream::operator<<(int*) /* linker, fun addr please? */
[...]
当您的代码要求调用其中任何一个时:
fun foo:
call f__<funky_mangled_name_to_say_this_is_f_for_&a>__
call f__<funky_mangled_name_to_say_this_is_f_for_&b>__
要调用的确切函数编码在损坏的函数名称中。生成的代码不依赖于&a
or的运行时值&b
。编译器知道在运行时会有这样的事情(你告诉过它),这就是它所需要的。它会让链接器填补空白(如果你没有兑现承诺,或者对你大喊大叫)。
对于您的补充,恐怕我对 constexpr 规则不够熟悉,但是我告诉我的两个编译器将在运行时评估此函数,据他们说,这会使代码不符合标准。(如果他们错了,那么上面的答案至少是不完整的。)
template <int* p, int* pp>
constexpr std::size_t f() {
return (p + 1) == (pp + 7) ? 5 : 10;
}
int main() {
int arr[f<&a, &b>()] = {};
}
C++14标准符合模式中的clang 3.5:
$ clang++ -std=c++14 -stdlib=libc++ t.cpp -pedantic
t.cpp:10:10: warning: variable length arrays are a C99 feature [-Wvla-extension]
int arr[f<&a, &b>()];
^
1 warning generated.
GCC g++ 5.1,相同模式:
$ g++ -std=c++14 t.cpp -O3 -pedantic
t.cpp: In function 'int main()':
t.cpp:10:22: warning: ISO C++ forbids variable length array 'arr' [-Wvla]
int arr[f<&a, &b>()];