我正在嘗試將函式宣告為具有受保護成員的類模板的朋友。下面是一個最小的例子。
template<int N> class myClass{
public:
friend void f(const myClass& c);
protected:
int a;
};
如果我現在將函式定義為
template<int N> void f(const myClass<N>& c){
std::cout << c.a;
};
然后它作業。
但是,如果我使用模板專業化
template<int N> void f(const myClass<N>& c);
template<> void f<1>(const myClass<1>& c){
std::cout << c.a;
};
它不再承認f自己是朋友,并抱怨說它a是受保護的成員。
為什么會這樣?我究竟做錯了什么?
uj5u.com熱心網友回復:
問題是朋友宣告friend void f(const myClass& c);是一個非模板朋友宣告。也就是說,您實際上是在與一個非模板免費函式成為朋友。這正是警告告訴您的內容:
warning: friend declaration 'void f(const myClass<N>&)' declares a non-template function [-Wnon-template-friend]
12 | friend void f(const myClass& c);
要解決這個問題,您需要為朋友宣告添加一個單獨的引數子句,如下所示:
template<int N> class myClass{
public:
template<int M> //added this parameter clause
friend void f(const myClass<M>& c);
protected:
int a;
};
作業演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/529533.html
標籤:C 模板朋友专业化
