下面的代碼不能編譯
使用 命名空間 std.com.cn>。
template<class T> class A;
template<class T> class B;
//@@@@@@@@@@@@@y。
template<class T>
class B{
int x=1;
public:
void write(A< T> x);
void add(A<T> x)。
};
template<class T>
class A{
int x=1;
public:
void write(B< T> x);
void add(B<T> x)。
};
template<class T> void A<T> 。 :write(B<T> x){cout<<"write generic A"<< endl;x。 add(*this); };
template<class T> void A<T> 。 :add(B<T> x){cout<<"add generic A"/span><<endl;}。
template<> void A<int> :: write(B<int> x){cout<<"write special A"<< endl;x。 add(*this); };
template<> void A<int> :: add(B<int> x){cout<<"add special A int"<< endl;}。
template<class T> void B<T> 。 :write(A<T> x){cout<<"write generic B"<< endl;x。 add(*this); };
template<class T> void B<T> 。 :add(A<T> x){cout<<"add generic B"/span><<endl;}。
template<> void B<int> :: write(A<int> x){cout<<"write special B"<< endl;x。 add(*this); };
template<> void B<int> :: add(A<int> x){cout<<"add special B"<< endl;}。
int main(){
B<int> b;
A<int> a;
b.write(a)。
}
因為A和B的專門的 "write "方法實體化了A或B的 "add "模板,當編譯器投訴時
錯誤:'void B<T>::add(A<T>) [with T = int] 的實體化后的特殊化
32 | template<> void B<int> 。 :add(A<int> x){cout<<"add special B"/span><<endl;}。
目前我還看不出如何對函式進行排序以避免這個問題,除了我放棄專業化。
非常感謝任何建議。
uj5u.com熱心網友回復:
你可以在每個類宣告之后宣告模板方法的特殊化:
#include <iostream>
使用 命名空間 std.com.cn>。
template<class T> class A;
template<class T> class B;
//@@@@@@@@@@@@@y。
template<class T>
class B{
int x=1;
public:
void write(A< T> x);
void add(A<T> x)。
};
// declare specializations:.
template<> void B<int>::write(A<int> x)。
template<> void B<int>::add(A<int> x) 。
template<class T>
class A{
int x=1;
public:
void write(B< T> x);
void add(B<T> x)。
};
// declare specializations:.
template<> void A<int> ::write(B<int> x) 。
template<> void A<int>::add(B<int> x)。
template<class T> void A<T> 。 :write(B<T> x){cout<<"write generic A"<< endl;x。 add(*this); };
template<class T> void A<T> 。 :add(B<T> x){cout<<"add generic A"/span><<endl;}。
template<> void A<int> :: write(B<int> x){cout<<"write special A"<< endl;x。 add(*this);}; //方法 "B<int> ::add(A<int> x)" 被呼叫但之前未被宣告或定義。
template<> void A<int> :: add(B<int> x){cout<<"add special A int"<< endl;}。
template<class T> void B<T> 。 :write(A<T> x){cout<<"write generic B"<< endl;x。 add(*this); };
template<class T> void B<T> 。 :add(A<T> x){cout<<"add generic B"/span><<endl;}。
template<> void B<int> :: write(A<int> x){cout<<"write special B"<< endl;x。 add(*this); };
template<> void B<int> :: add(A<int> x){cout<<"add special B"<< endl;}。
int main(){
B<int> b;
A<int> a;
b.write(a)。
}
代碼中有一個關于方法B<int>::add(A<int> x)在A<int>:write(B<int> x)中被呼叫,但之前沒有宣告或定義。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/326641.html
標籤:
