【发布时间】:2021-01-01 01:04:01
【问题描述】:
使用类型特征,我可以执行以下操作:
template<typename Rect> Rect& move(Rect& rc, size_type<Rect> delta)
{
rc.left += delta.width;
rc.right += delta.width;
rc.top += delta.height;
rc.bottom += delta.height;
return rc;
}
template<typename Rect> Rect& move(Rect& rc, point_type<Rect> to)
{
int w = w(rc);
int h = h(rc);
rc.left = to.x;
rc.top = to.y;
rc.right = rc.left + w;
rc.bottom = rc.top + h;
return rc;
}
但是如何在不更改函数名称的情况下允许传递任何大小和点类型?显然我不能这样做:
template<typename Rect, typename Size> Rect& move(Rect& rc, Size delta);
template<typename Rect, typename Point> Rect& move(Rect& rc, Point to);
我想做的是
template<typename Rect, typename Size /*if Size::width, use this*/> Rect& move(Rect& rc, Size size);
template<typename Rect, typename Point /*if Point::x, use this*/> Rect& move(Rect& rc, Point to);
即选择重载取决于模板参数是否具有特定成员。用c++可以吗?
【问题讨论】:
标签: c++ templates overloading metaprogramming template-meta-programming