A min =在C ++中成语? [英] A min= idiom in C++?
问题描述
我们使用
x + = y
而不是
x = x + y
对于 *,/, -
那么,
x min = y
而不是
x = std :: min(x,y)
?
这个命令有一个常用的成语,不需要用另一个操作符扩展语言的这当然不是惯用的,但您可以使用命名运算符(请参阅这些问与答这里和此处,由@Yakk和@KonradRudolph开发),然后写入
x< min> = y;
和
operator>
,结合一个聪明的包装named_operator
。完整的代码由上面的链接给出,但使用像模板< typename T1,typename T2,typename F&
inline auto operator>(named_operator_lhs< T1,F> const& lhs,T2 const& rhs)
- > decltype(lhs.f(std :: declval< T1>(),std :: declval< T2>()))
{
return lhs.f(lhs.value,rhs);
}
使用
std :: min
作为模板参数F
的模板参数,将用lhs和rhs的min更新表达式的lhs。We use
x += y
instead of
x = x + y
And similarly for
*,/,-
and other operators. Well, what aboutx min= y
instead of
x = std::min(x, y)
? Is there a commonly-used idiom for this command, not requiring the (impossible) extension of the language with another operator?
解决方案It's certainly not idiomatic, but you might be able to use something called named operators (see these Q&As here and here, developed by @Yakk and @KonradRudolph), and write
x <min>= y;
which is made possible by overloading
operator<
andoperator>
, combined with a clever wrappednamed_operator
. The full code is given by the link above, but uses code liketemplate <typename T1, typename T2, typename F> inline auto operator >(named_operator_lhs<T1, F> const& lhs, T2 const& rhs) -> decltype(lhs.f(std::declval<T1>(), std::declval<T2>())) { return lhs.f(lhs.value, rhs); }
Using
std::min
as template argument for the template parameterF
, would update the lhs of the expression with the min of the lhs and rhs.这篇关于A min =在C ++中成语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!