【问题标题】:Implicit conversion with operator float() and float() const with static members使用 operator float() 和 float() 隐式转换 const 与静态成员
【发布时间】:2017-09-28 15:45:45
【问题描述】:

我在尝试超载 operator float()operator float() const 时遇到了问题。我以为我可以使用这两种重载来为“做事”和“只是阅读”提供不同的版本......但事实证明,对于包含这些重载的类的静态实例,我不能。

将问题归结为以下内容:

// Does some math and should convert to float
struct ToFloat
{
  // float conversion here
  operator float()
  {
    cout << "called operator float() of " << s << "\n";
    f += 1.0f;
    return f;
  }

  // just get current value here
  operator float() const
  {
    cout << "called operator float() *const* of " << s << "\n";
    return f;
  }

  float f;
  std::string s;
};

// Uses a static and a normal member of ToFloat
struct Container
{
  // return both instances (with some more math before)
  operator float()
  {
    return s * m;
  }

  // just provide read access
  operator float() const
  {
    return s * m;
  }

  static inline ToFloat s { 1.0f, "static" };
  ToFloat m { 1.0f, "member" };
};

// Uses the container, but must also provide read-only access
struct Use
{
  // Give me operator float() of my container
  float get()
  {
    return c;
  }

  // Give me operator float() const of my container
  float getC() const
  {
    return c;
  }

  Container c {};
};

int main()
{
  Use u {};

  printf("getC() %f \n\n", u.getC());
  printf("get() %f \n\n", u.get());
  printf("getC() %f \n\n", u.getC());
}

这会产生以下输出...

called operator float() of static
called operator float() *const* of member
getC() 2.000000 

called operator float() of static
called operator float() of member
get() 6.000000 

called operator float() of static
called operator float() *const* of member
getC() 8.000000 

我真的不明白为什么ToFloat 的静态实例总是使用非const 转换,即使是从声明为const 的函数调用?这里适用什么规则?

【问题讨论】:

  • 静态成员不是const,只是因为类的一个实例是const。从该实例的代码中,它也不会出现const。不相关,但使用 float 而不是默认的 double 通常只是发出愚蠢警告的邀请,维护人员会浪费时间试图弄清楚你为什么要这样做。
  • 我的目标平台不支持双硬件。
  • @Cheersandhth.-Alf 关于floatdouble:真的吗?我想说的是,在大量的数字运算代码中,很多人都在思考double 的精度在哪里值得速度和内存成本。
  • @Angew:确实,有时float 很有用:它在语言中是有原因的。当你有无数个值时,它是空间的一半,当你或多或少地按顺序处理它们时,这也是你的速度。但一般默认float 不太方便,有时比double 慢,而且通常没有优势。 OP 的代码中没有任何内容表明float 的合理用例。但是,他解释说这是由于硬件限制。

标签: c++ static type-conversion constants


【解决方案1】:

静态数据成员Container::s 只是类型ToFloat。它总是直接访问,从不通过this 的隐式取消引用。换句话说,容器的const 操作符实际上是这样的:

operator float() const
{
  return Container::s * this->m;
}

由此可见,Container::s 没有理由仅仅因为thisconst Container * 而被视为const。如果您希望它被视为const,您必须明确限定它:

operator float() const
{
  return std::as_const(s) * m;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多