这段代码能够运行并且从向量中返回一个指向foo{5}
的迭代器:
struct foo {
int value;
};
auto main() -> int {
auto ints = std::vector<foo>{{3}, {2}, {5}, {6}, {7}, {0}, {4}, {6}};
std::ranges::sort(ints, {}, &foo::value);
auto it = std::upper_bound(
ints.begin(), ints.end(),
4,
[](const int v, const foo f) {
return v < f.value;
}
);
}
然而,这段代码无法通过编译:
struct foo {
int value;
};
auto main() -> int {
auto ints = std::vector<foo>{{3}, {2}, {5}, {6}, {7}, {0}, {4}, {6}};
std::ranges::sort(ints, {}, &foo::value);
auto it = std::ranges::upper_bound( // the only change - added ::ranges
ints,
4,
[](const int v, const foo f) {
return v < f.value;
}
);
std::cout << it->value;
}
这种行为的变化是故意还是偶然导致的?
错误信息归结为未满足以下约束条件:
note: the expression 'is_invocable_v<_Fn, _Args ...> [with _Fn = main::._anon_76&; _Args = {int&, int&}]' evaluated to 'false'
好的,是的,你不能使用两个int&
来调用它。我怀疑这可能是有意为之的,因为“标准”的方法是使用投影,例如:
struct foo {
int value;
};
auto main() -> int {
auto ints = std::vector<foo>{{3}, {2}, {5}, {6}, {7}, {0}, {4}, {6}};
std::ranges::sort(ints, {}, &foo::value);
auto it = std::ranges::upper_bound(ints, 4, {}, &foo::value); // using projection
std::cout << it->value;
}
这是合理的吗?看着std::ranges::upper_bound
模板参数的相当复杂签名并没有为我提供任何启发。