C++ C++;隐式地将可构造的结构转换为成员
我觉得这不太可能,但我想看看函数是否可以从一个简单包装的结构推断出它的参数。例如:C++ C++;隐式地将可构造的结构转换为成员,c++,struct,gdi,implicit-conversion,C++,Struct,Gdi,Implicit Conversion,我觉得这不太可能,但我想看看函数是否可以从一个简单包装的结构推断出它的参数。例如: 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
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);
}
void OnPaint(graphics g)
{
g.rectangle(1, 2, 3, 4);
}
欢迎任何建议,因为这在C++(或任何编程语言)中可能是不可能的。
< P>从注释中,我不知道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;
}
};
为什么在这里简单地实现明显的
操作符float
是不够的?实际上我不知道这是可能的。这就足够了。谢谢。根据HDC
类型,您可以使用const
ref,并可能标记或添加方法const
:操作符const HDC&()const
@Jarod42返回const引用与句柄副本相比有什么好处?我将使函数const however返回引用,以避免复制对象的开销。const
引用确保对象不能被修改。@SamVarshavchik这是真的,但HDC已经像一个不透明指针,非常小(4字节)。我真的看不到通过引用传递而不是通过值复制的好处。我还缺什么吗?是的。如果使用了任何现代C++编译器,返回< <代码> <代码> >代码> const ,使用<代码>内联函数通常防止胖手指键入<代码> = />代码>当您指的是代码>=时,不增加任何额外开销。