gpt4 book ai didi

c++ - 基于条件的模板重载

转载 作者:行者123 更新时间:2023-12-03 07:07:10 24 4
gpt4 key购买 nike

使用类型特征,我可以执行以下操作:

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++中有可能吗?

最佳答案

What I want to do is


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);

I.e. choosing an overload depends on whether a template argument has a particular member. Is it possible in c++?


如果您至少可以使用C++ 11 ...您是否通过尾随返回类型和 decltype()尝试使用SFINAE?
我的意思是...
template <typename Rect, typename Size>
auto move (Rect & rc, Size size)
-> decltype( size.width, rc );
// .............^^^^^^^^^^^ <-- note this

template <typename Rect, typename Point>
auto move(Rect& rc, Point to)
-> decltype( to.x, rc );
// .............^^^^^ <-- and note this
显然,如果您用另一个同时带有 move()with成员的参数调用 x,则此方法不起作用:编译器不知道选择哪个 move()
这个怎么运作?
很简单:主要词是SFINAE,这意味着替换失败不是错误。
计算 decltype()返回所包含表达式的类型,因此(例如)从
   decltype( size.width, rc );
逗号运算符丢弃 size.width,如果可用,则丢弃 (这很重要!),并保留rc,因此decltype()返回rc的类型(如果size.width存在!)。
但是,如果size.width不存在,会发生什么?
您有一个“替换失败”。那个“不是错误”,但是从可用的move()函数集中删除了这个move()重载版本。

关于c++ - 基于条件的模板重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63882085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com