模板类容器存在自动转换问题

发布于 2024-10-13 04:12:14 字数 785 浏览 1 评论 0原文

我有以下代码:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

荒人说梦 2024-10-20 04:12:14

这似乎是 vc++ 中的一个小故障。如果我添加一个字符串

 x = x* (*&v[0]); 

BEFORE the string

x = x*v[0];

(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

 x = x* (*&v[0]); 

BEFORE the string

x = x*v[0];

(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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文