-3
我不明白爲什麼這個工程:爲什麼我不能將局部變量引用爲非類型模板參數?
#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
爲什麼我的問題downvoted。它清晰簡潔,並且是一個實際的C++問題 – Kam 2014-09-30 22:55:35
編譯器無法真實地知道包含函數的堆棧框架在哪裏。它可能在多個函數調用中有所不同。 (雖然在這個例子中,重新輸入'main'將會是UB,但它可以是任何函數。) – 5gon12eder 2014-09-30 22:55:53
對不起,更好的重複會是:http://stackoverflow.com/questions/9218615/function-template -with參考模板參數 – Csq 2014-09-30 22:58:46