[英]Overload operator<< for template class
我有重載operator <<為模板類的問題。 我使用的是Visual Studio 2010,這是我的代碼。
#ifndef _FINITEFIELD
#define _FINITEFIELD
#include<iostream>
namespace Polyff{
template <class T, T& n> class FiniteField;
template <class T, T& n> std::ostream& operator<< (std::ostream&, const FiniteField<T,n>&);
template <class T, T& n> class FiniteField {
public:
//some other functions
private:
friend std::ostream& operator<< <T,n>(std::ostream& out, const FiniteField<T,n>& obj);
T _val;
};
template <class T, T& n>
std::ostream& operator<< (std::ostream& out, const FiniteField<T,n>& f) {
return out<<f._val;
}
//some other definitions
}
#endif
在主要我只是
#include"FiniteField.h"
#include"Integer.h"
#include<iostream>
using std::cout;
using namespace Polyff;
Integer N(5);
int main () {
FiniteField<Integer, N> f1;
cout<< f1;
}
其中Integer
只是int
的包裝器,具有我需要的一些特殊功能。
但是,當我編譯上面的代碼時,我得到了錯誤C2679,它表示binary '<<' : no operator found which takes a right-hand operand of type 'Polyff::FiniteField<T,n>' (or there is no acceptable conversion)
我還嘗試刪除友元聲明中的參數,以便代碼變為:
friend std::ostream& operator<< <> (std::ostream& out, const FiniteField<T,n>& obj);
但這會產生另一個錯誤:C2785: 'std::ostream &Polyff::operator <<(std::ostream &,const Polyff::FiniteField<T,n> &)' and '<Unknown>' have different return types
所以我想知道我應該如何更改代碼以便編譯以及為什么? 謝謝!
-------------------------編輯於2012.12.31 -------------------- -------
代碼現在用g ++編譯。 這是github存儲庫。
這似乎按預期工作:
namespace Polyff{
template <class T, T* n> class FiniteField;
template <class T, T* n> std::ostream& operator<< (std::ostream&, const FiniteField<T,n>&);
template <class T, T* n> class FiniteField {
public:
//some other functions
private:
friend std::ostream& operator<< <T,n>(std::ostream& out, const FiniteField<T,n>& obj);
T _val;
};
template <class T, T* n>
std::ostream& operator<< (std::ostream& out, const FiniteField<T,n>& f) {
return out << f._val.n; // I added the field of my Integer class
}
//some other definitions
}
struct Integer{
Integer() : n(0){}
Integer(int nn) : n(nn){}
int n;
};
using std::cout;
using namespace Polyff;
Integer N(5);
int main () {
FiniteField<Integer, &N> f1;
cout<< f1;
}
我剛剛在模板參數中用對象的指針替換了引用,因為指向全局對象(靜態或非靜態)的指針是在編譯時(或至少鏈接時)已知的信息。 我不知道接受引用的語言。
請注意,在此示例中,將打印0
因為它對應於_val
的默認構造。
我試圖在我的Visual C ++ 2010上編譯你的代碼。我得到了和你一樣的錯誤。
在你的代碼中,Visual實際上有兩件事情不喜歡:
這使我的工作!
您應該使用普通變量( T n
而不是T& n
)替換引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.