【发布时间】:2012-12-31 08:31:55
【问题描述】:
我在为模板类重载 operator
#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++ 编译。 Here 是 github 仓库。
【问题讨论】:
-
虽然我不完全确定 T& 的用途是什么,但我不确定它是否重要。我只用
Polyff::FiniteField<int,N> obj尝试了您的第一个代码列表,其中 N 是全局int。当我然后cout << obj << endl;时,它工作正常(逐步调试以确保)。你的 Integer 类可能有问题吗? (顺便说一下,在 Mac OS X 10.8.1 上使用 LLVM 4.1)。 -
感谢您的建议。我刚刚用 int 测试过,还是不行。但是,当我尝试使用 g++ 编译器编译我的代码时,一切正常,我的 Integer 包装器类也是如此。这是 vs2010 编译器的一些错误吗?顺便说一句,参数“T&N”是建立在它所基于的积分域上的有限域的上限。如果你不知道我在说什么并且觉得它很烦人,你可以通过搜索“有限域”找到更多相关信息。
-
Clang++ 和 G++ 都可以编译它(在添加了
Integer的定义和FiniteField的默认构造函数之后,您应该包含它以使代码完整和独立)。注:_FINITEFIELD是 reserved name,为您的包含保护选择不同的宏。 -
如果你使用 Polyff::operator
-
这将是有线的,因为
g++能够推断出如何引用operator<<。我想我只会认为这是 VS2010 编译器的错误。顺便说一句,这个程序只是我对 C++ 模板的小尝试,不是一个严肃项目的任何部分。感谢大家的帮助!
标签: c++ visual-studio-2010 templates operator-overloading friend-function