【问题标题】:Container of template class with automatic conversion problem模板类的容器有自动转换问题
【发布时间】:2011-01-21 08:56:55
【问题描述】:

我有以下代码:

#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 2005 express 和 2010 express 中编译会出现以下错误:

错误 C2676:二进制“*”:“已修复” 未定义此运算符或 转换为可接受的类型 预定义运算符

如果我取消注释 main 中的三行中的任何一行(注释额外的向量),它将编译。如果我使用 gcc 它将编译。任何人都可以提示这是为什么吗?

代码是一个大型项目的简化版本,因此很遗憾这三种解决方案不适合我。

【问题讨论】:

    标签: c++ templates compiler-errors


    【解决方案1】:

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

     x = x* (*&v[0]); 
    在字符串
    x = x*v[0];
    之前(产生错误)然后错误消失(我使用 vc 2010 express)。 GCC 编译这段代码没有错误,但只有在将类重命名为其他东西之后(否则它会抱怨这个名字的歧义,我不知道为什么,也许它也出现在一些 gcc 头文件中)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 2022-12-06
    • 2011-05-27
    • 2021-11-15
    • 2014-01-16
    相关资源
    最近更新 更多