使用静态成员的float()和float()const的隐式转换



我在尝试超载operator float()operator float() const时遇到了一个问题。我以为我可以使用两个过载来为"做事"one_answers"读"提供不同的版本...但是事实证明,在类静态实例的情况下,包含这些超载的静态实例。

将问题归结为几乎减少了:

// 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 nn", u.getC());
  printf("get() %f nn", u.get());
  printf("getC() %f nn", 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的函数中调用?什么规则在这里适用?

静态数据成员Container::s仅为ToFloat类型。它始终直接通过this的隐式解除直接访问。换句话说,容器的const操作员实际上是这样:

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

由此,显然没有理由将Container::s视为const,仅仅是因为thisconst Container *。如果您希望将其视为const,则必须明确符合资格:

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

最新更新