【发布时间】:2014-09-30 22:50:21
【问题描述】:
我不明白为什么会这样:
#include <iostream>
template<int& obj>
void foo() { obj = 42; }
int i;
int main()
{
foo<i>();
std::cout << i;
}
但事实并非如此:
#include <iostream>
template<int& obj>
void foo() { obj = 42; }
int main()
{
int i;
foo<i>();
std::cout << i;
}
//error: the value of 'i' is not usable in a constant expression
【问题讨论】:
-
为什么我的问题被否决了。它清晰简洁,是一个实际的 C++ 问题
-
编译器实际上无法知道包含函数的堆栈帧在哪里。它甚至可能在多个函数调用中有所不同。 (尽管在本例中,重新输入
main无论如何都会是 UB,但它可以是任何函数。) -
抱歉,更好的副本应该是:stackoverflow.com/questions/9218615/…