簡體   English   中英

使用 mem_fn 代替 mem_fun

[英]Using mem_fn instead of mem_fun

我正在嘗試使用以下答案: String To Lower/Upper in C++但我使用的是 C++17,這意味着該答案已被棄用。

bind替換bind1st很簡單,現在我想用mem_fn替換mem_fun ,但由於某種原因,這對我來說並不那么簡單。

我嘗試了以下替換:

auto greet = std::mem_fn<wchar_t(wchar_t)>(&ctype<wchar_t>::toupper);

這給了我“找不到匹配的重載 function”錯誤。 為什么? 如果我想堅持std::transform ,我該如何解決?

避免std::bindstd::mem_fn和朋友,而是使用 lambdas 更簡單。

例如:

std::transform(in.begin(), in.end(), out.begin(), [&ct](wchar_t c) {
    return ct.toupper(c);
});

正確的寫法是:

auto greet = std::mem_fn<wchar_t(wchar_t) const, std::ctype<wchar_t>>(
    &std::ctype<wchar_t>::toupper);

或者實際上你不需要兩個模板參數,只需要第一個:

auto greet = std::mem_fn<wchar_t(wchar_t) const>(&std::ctype<wchar_t>::toupper);

您缺少的重要部分是const :它是一個const成員 function,您需要完整的類型。


但是你最好寫 lambda:

auto greet = [](std::ctype<wchar_t> const& ct, wchar_t c) {
    return ct.toupper(c);
};

std::mem_fn聲明中可以看到,有兩個模板參數,第一個是 function 簽名,第二個是 class 類型。 問題是您只明確指定了 function 簽名而不是 class 類型,這使得編譯器必須從參數中推斷出它。 並且參數是重載集std::ctype<wchar_t>::toupper ,您沒有通過強制轉換解決。

解決方法是將std::ctype<wchar_t>::toupper指針顯式轉換為所需的成員指針。 之后,您無需顯式指定std::mem_fn的模板參數。

using toupper_t = wchar_t (std::ctype<wchar_t>::*)(wchar_t) const;
auto greet = std::mem_fn(static_cast< toupper_t >(&std::ctype<wchar_t>::toupper));

但是,當然,改用 lambda 會容易得多。

暫無
暫無

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

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