[英]What does boost::hana::always do more than just “always return its first argument”?
At the doc page of boost::hana::always
I read that在
boost::hana::always
的文档页面上,我读到了
always(x)
is a function such thatalways(x)
是一个 function 使得always(x)(y...) == x
for any
y...
.对于任何
y...
This makes me think that it shouldn't behave any differently than this lambda: [](auto const&...){ return false; }
这让我认为它的行为不应该与这个 lambda:
[](auto const&...){ return false; }
[](auto const&...){ return false; }
. [](auto const&...){ return false; }
。
However it does.然而确实如此。 For instance, the following code prints
11
, but if I change the third lambda to hana::always(false)
, then it prints 00
, revealing that always
is swallowing any argument.例如,下面的代码打印
11
,但是如果我将第三个 lambda 更改为hana::always(false)
,那么它会打印00
,这表明它always
在吞噬任何参数。
#include <boost/hana/functional/always.hpp>
#include <boost/hana/functional/overload.hpp>
#include <iostream>
auto fun = boost::hana::overload(
[](int){ return true; },
[](double){ return true; },
[](auto const&...){ return false; }
);
int main() {
std::cout << fun(1) << fun(1.0) << std::endl;
}
By the way, I've just discovered boost::hana::overload_linearly
, which is not an alternative to boost::hana::overload
in this case (because as much as always
would not get all the calls, it would be the [](int){ return true; }
to be greedy), but it's good to know of it.顺便说一句,我刚刚发现
boost::hana::overload_linearly
,在这种情况下它不是boost::hana::overload
的替代品(因为always
不会得到所有的调用,它会是[](int){ return true; }
贪婪),但很高兴知道这一点。
In fact, always
has different overloads (as it handles reference as return value).事实上,
always
有不同的重载(因为它将引用作为返回值处理)。
so, with a simplified version:因此,使用简化版本:
template <typename T>
struct my_always
{
T res;
template <typename ...&& Ts>
T& operator ()(Ts&&...) /* mutable */ { return res; } // #1
template <typename ...&& Ts>
const T& operator ()(Ts&&...) const { return res; } // #2
};
then然后
auto fun = boost::hana::overload(
my_always<bool>{ false }, // #1 & #2
[](int){ return true; } // #3
);
std::cout << fun(1);
Possible overloads are:可能的重载是:
bool& my_always<bool>::operator ()(int&&)
#1 bool& my_always<bool>::operator ()(int&&)
#1const bool& my_always<bool>::operator ()(int&&) const
#2 const bool& my_always<bool>::operator ()(int&&) const
#2bool lambda::operator() (int) const
#3 bool lambda::operator() (int) const
#3 All are viable here, but #1
is the best match (as fun
is not const
(and int
is not better than int&&
)).在这里一切都是可行的,但
#1
是最好的匹配(因为fun
不是const
(并且int
并不比int&&
更好))。
With const
fun
, #3 would be the best match (#1 not viable, tie-breaker between #2 and #3 is template status).使用
const
fun
,#3 将是最佳匹配(#1 不可行,#2 和 #3 之间的决胜局是模板状态)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.