此代碼是從 「C++程序設計語言」 由Bjarne Stroustrup的(實例化的C.13.8.3處裝訂)在哪一點發生模板實例化綁定?
template <class T>
void f(T value)
{
g(value);
}
void g(int v);
void h()
{
extern g(double);
f(2);
}
他提到:
Here, the point of instantiation for f() is just before h(), so the g() called in f() is the global g(int) rather than the local g(double). The definition of ‘‘instantiation point’’ implies that a template parameter can never be bound to a local name or a class member.
void h()
{
struct X {}; // local structure
std::vector<X> v; // error: can't use local structure as template parameter
}
我的問題是:
第一個代碼爲什麼要工作?
g()
稍後聲明,並且我確實在G ++ 4.9.2中出現錯誤g
未在此處聲明。extern g(double) - 這是如何工作的?既然返回值在函數重載的情況下不重要,那麼我們可以在前向聲明中忽略它?
f()的實例化點就在h()之前 - 爲什麼?在
f(2)
被調用時它會被實例化是否合乎邏輯?在我們稱之爲的地方,g(double)
將在此範圍內。「實例化點」的定義意味着模板參數永遠不能綁定到本地名稱或類成員 - 這是否改變了C++ 14?我遇到C++(G ++ 4.9.2)的錯誤,但不會因C++ 14(G ++ 4.9.2)而出錯。
「在1985年,C++編程語言的第一個版本發佈,這成爲該語言的明確的參考,因爲**有沒有但官方標準**「。 [wiki](https://en.wikipedia.org/wiki/C%2B%2B#History)所以它在'C++ 11'和'C++ 14'之間沒有變化。它在「預標準化」和標準化之間改變。 – bolov
檢查14.6.4.1 [temp.point]規則 – AndyG
也搜索兩個階段名稱查找 – bolov