![](/img/trans.png)
[英]Why does explicit method specialization of a template class work without its prototype declaration inside the class
[英]Why does this explicit template specialization does not work?
從此代碼:
// Example program
#include <iostream>
#include <string>
struct Z { static const int z = 1; };
struct Y { static const int y = 2; };
template <typename A> struct TE { int foo(); int bar(); };
template <> int TE<Y>::bar() { return foo(); }
template <typename A> int TE<A>::bar() { return foo(); }
template <> int TE<Y>::foo() { return Y::y; }
template <typename A> int TE<A>::foo() { return A::z; }
template struct TE<Z>;
template struct TE<Y>;
int main()
{
TE<Z> z;
TE<Y> y;
std::cout << z.bar() << std::endl;
std::cout << y.bar() << std::endl;
return 0;
}
這個錯誤
21:28: error: specialization of 'int TE<A>::foo() [with A = Y]' after instantiation
In instantiation of 'int TE<A>::foo() [with A = Y]':
13:12: required from here
28:15: error: 'z' is not a member of 'Y'
In member function 'int TE<A>::foo() [with A = Y]':
29:1: warning: control reaches end of non-void function [-Wreturn-type]
這些實現在單獨的cpp文件中完成。 並且這些結構位於標頭中,即典型的顯式模板實例化。
為什么這樣做
int TE<Y>::bar() { return foo(); }
嘗試使用這個
template <typename A> int TE<A>::foo() { return A::z; }
代替這個
template <> int TE<Y>::foo() { return Y::y; }
http://en.cppreference.com/w/cpp/language/template_specialization
顯式專業化只能出現在與主模板相同的名稱空間中,並且必須出現在非專業化模板聲明之后 。
另外,您需要遵循“單一定義規則”(ODR)。 因此,通常您會在同一標頭中提供實現。
問題是在實例化時間bar
您的foo
專業化是未知的,因此兩個 bar
的foo
都引用foo
基本模板。
如第一條錯誤消息所述,當編譯器進入Y
專業化級別時,基本模板已使用A = Y
實例化。
第二個錯誤是在大型C ++傳統中由於專業化失敗而導致的“級聯錯誤”。
如果重新排列定義,它將起作用:
template <typename A> int TE<A>::foo() { return A::z; }
template <> int TE<Y>::foo() { return Y::y; }
template <typename A> int TE<A>::bar() { return foo(); }
template <> int TE<Y>::bar() { return foo(); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.