代码之家  ›  专栏  ›  技术社区  ›  Michael Choi Peter Alexander

C++将平凡的可构造结构隐式转换为成员

  •  1
  • Michael Choi Peter Alexander  · 技术社区  · 6 年前

    我觉得它不太可能,但我想看看函数是否可以从一个简单的包装结构中推导出它的参数。例如:

    struct wrapped_float
    {
      float f;
    
      wrapped_float(float f) : f(f) {}
    };
    
    float saxpy(float a, float x, float y)
    {
      return a * x + y;
    }
    
    int main()
    {
      wrapped_float a = 1.1, x = 2.2, y = 3.3;
    
      auto result = saxpy(a, x, y); // ofc compile error
    }
    

    其背后的动机是用设备上下文句柄(HDC)围绕GDI调用创建一个轻量级包装器。有很多使用HDC的遗留代码,我想逐步重构这些代码。我的策略是围绕HDC做一个轻量级的包装,如下所示:

    #include <Windows.h>
    
    struct graphics
    {
      HDC dc;
    
      graphics(HDC dc) : dc(dc) {}
    
      void rectangle(int x, int y, int w, int h)
      {
        Rectangle(dc, x, y, x + w, y + h);
      }
    };
    
    void OnPaint(HDC dc)
    {
      Rectangle(dc, 1, 2, 3, 4);
    }
    
    int main()
    {
      HDC dc;
      // setup dc here
      graphics g = dc;
    
      OnPaint(g);
    }
    

    因此,如果g可以隐式地转换为hdc,那么所有遗留代码都将正常编译,但我可以慢慢地重构代码,使其变成这样:

    void OnPaint(graphics g)
    {
      g.rectangle(1, 2, 3, 4);
    }
    

    任何建议也是受欢迎的,因为这在C++(或任何编程语言)中可能是不可能的。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Michael Choi Peter Alexander    6 年前

    从注释中,我不知道C++有一个抛出操作符。简单的解决方案是添加:

    struct graphics
    {
      HDC dc;
    
      graphics(HDC dc) : dc(dc) {}
    
      void rectangle(int x, int y, int w, int h)
      {
        Rectangle(dc, x, y, x + w, y + h);
      }
    
      operator HDC()
      {
        return dc;
      }
    };