模板类容器存在自动转换问题
我有以下代码:
#include <vector>
template<int Wt = 0>
class fixed {
public:
explicit fixed(double val = 0) {
operator=(val);
}
~fixed(){}
operator double() const {
return v_;
}
double operator =(const double &d){
if (d>Wt)
v_ = Wt;
else
v_ = d;
return v_;
}
private:
double v_;
};
int main(){
fixed<5> x;
std::vector<fixed<6> > v(5);
//std::vector<fixed<6> > v(5,0);
//fixed<6> y;
//v[0] = 0;
x = x*v[0];
}
在 VS 2005express 和 2010express 中编译出现以下错误:
错误 C2676:二进制“*”:“已修复” 没有定义这个运算符或 转换为可接受的类型 预定义运算符
如果我取消注释 main 中三行中的任何一行(注释额外的向量),它将编译。如果我使用 gcc 它将编译。有人能暗示这是为什么吗?
该代码是一个较大项目的简化版本,因此不幸的是,这三个解决方案不适合我。
I have the following code:
#include <vector>
template<int Wt = 0>
class fixed {
public:
explicit fixed(double val = 0) {
operator=(val);
}
~fixed(){}
operator double() const {
return v_;
}
double operator =(const double &d){
if (d>Wt)
v_ = Wt;
else
v_ = d;
return v_;
}
private:
double v_;
};
int main(){
fixed<5> x;
std::vector<fixed<6> > v(5);
//std::vector<fixed<6> > v(5,0);
//fixed<6> y;
//v[0] = 0;
x = x*v[0];
}
Compiling in VS 2005 express and 2010 express gives the following error:
error C2676: binary '*' : 'fixed'
does not define this operator or a
conversion to a type acceptable to the
predefined operator
If I uncomment any of the three lines in the main (commenting the extra vector), it will compile. If I use gcc it will compile. Can anybody give a hint to why this is?
The code is a simplified version of a larger project so the three solutions are unfortunately not options for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这似乎是 vc++ 中的一个小故障。如果我添加一个字符串
BEFORE the string
(which produced the error) then the error disappears (I use vc 2010 express). GCC compiles this code w/o errors, but only after renaming class fixed to something else (otherwise it complains about ambiguity of this name, i don't know exactly why, maybe it also appears in some gcc headers)
It seems as a glitch in vc++. If I ADD a string
BEFORE the string
(which produced the error) then the error disappears (I use vc 2010 express). GCC compiles this code w/o errors, but only after renaming class fixed to something else (otherwise it complains about ambiguity of this name, i don't know exactly why, maybe it also appears in some gcc headers)