[英]std::reduce with functor
我嘗試使用帶有仿函數的std::reduce
來計算數組中的字符數。 GCC 在 MSVC 中編譯和工作時出現錯誤。 鏈接在這里
#include <iostream>
#include <array>
#include <numeric>
#include <cstring>
int main()
{
std::array arr{ "Mickey","Minnie","Jerry" };
struct StringLength
{
auto operator()(const char* l, size_t r)
{
return strlen(l) + r;
}
auto operator()(size_t l, const char* r)
{
return l + strlen(r);
}
auto operator()(const char* l, const char* r)
{
return strlen(l) + strlen(r);
}
auto operator()(size_t l, size_t r)
{
return l + r;
}
};
std::cout << std::reduce(arr.begin(), arr.end(), size_t{}, StringLength());
// this ^ works in MSVC
}
GCC 10.1 錯誤,因為重要信息不應隱藏在鏈接后面:
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/numeric:
In instantiation of '_Tp std::reduce(_InputIterator, _InputIterator, _Tp, _BinaryOperation)
[with _InputIterator = const char**; _Tp = long unsigned int;
_BinaryOperation = main()::StringLength]':
<source>:29:78: required from here
/opt/compiler-explorer/gcc-10.1.0/include/c++/10.1.0/numeric:263:21: error:
static assertion failed
263 | static_assert(is_convertible_v<value_type, _Tp>);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我同意dewaffled認為這是一個錯誤。 std::reduce
的libstdc++
實現如下所示:
template<typename InputIt, typename Tp, typename BinOp>
Tp reduce(InputIt first, InputIt last, Tp init, BinOp binary_op) {
using value_type = typename iterator_traits<InputIt>::value_type;
static_assert(is_invocable_r_v<Tp, BinOp&, Tp&, Tp&>);
static_assert(is_convertible_v<value_type, Tp>);
// ...
}
我無法在標准中找到迭代器的value_type
必須可轉換為Tp
的要求。 而且,這個要求根本沒有必要。 如果您刪除該 static 斷言,您的代碼將正常編譯。
從 GCC Bugzilla 更新
已為 9.5、10.4 和 11.2 修復。
喬納森維克利,2021-06-18
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.