簡體   English   中英

boost::hana::always 做的不僅僅是“總是返回它的第一個參數”嗎?

[英]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&&) #1
  • const bool& my_always<bool>::operator ()(int&&) const #2
  • bool lambda::operator() (int) const #3

在這里一切都是可行的,但#1最好的匹配(因為fun不是const (並且int並不比int&&更好))。

使用const fun ,#3 將是最佳匹配(#1 不可行,#2 和 #3 之間的決勝局是模板狀態)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM