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

C++ implicitly transform trivially constructable struct to member

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

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++(或任何编程语言)中可能根本不可能。

根据评论,我不知道 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;
  }
};