![](/img/trans.png)
[英]Define struct having more than 40 fields using BOOST_HANA_DEFINE_STRUCT in Boost::Hana
[英]What does boost::hana::always do more than just “always return its first argument”?
在boost::hana::always
的文檔頁面上,我讀到了
always(x)
是一個 function 使得always(x)(y...) == x
對於任何
y...
這讓我認為它的行為不應該與這個 lambda: [](auto const&...){ return false; }
[](auto const&...){ return false; }
。
然而確實如此。 例如,下面的代碼打印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;
}
順便說一句,我剛剛發現boost::hana::overload_linearly
,在這種情況下它不是boost::hana::overload
的替代品(因為always
不會得到所有的調用,它會是[](int){ return true; }
貪婪),但很高興知道這一點。
事實上, always
有不同的重載(因為它將引用作為返回值處理)。
因此,使用簡化版本:
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
};
然后
auto fun = boost::hana::overload(
my_always<bool>{ false }, // #1 & #2
[](int){ return true; } // #3
);
std::cout << fun(1);
可能的重載是:
bool& my_always<bool>::operator ()(int&&)
#1const bool& my_always<bool>::operator ()(int&&) const
#2bool lambda::operator() (int) const
#3 在這里一切都是可行的,但#1
是最好的匹配(因為fun
不是const
(並且int
並不比int&&
更好))。
使用const
fun
,#3 將是最佳匹配(#1 不可行,#2 和 #3 之間的決勝局是模板狀態)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.