为什么std::isupper不能直接应用于std::any_of,而isupper(来自C头文件)可以



见下面代码:

#include <algorithm>
#include <ctype.h>
#include <cctype>
#include <string>
int main() {
std::string str = "a String";

// compile fail: template deduction fail for _Pred
// return std::any_of(str.begin(), str.end(), std::isupper);
// OK:
return std::any_of(str.begin(), str.end(), isupper); // or ::isupper
}

std::isupperisupper根据cppreference.com有相同的声明:

定义在header

int isupper(int ch);

定义在header

int isupper(int ch);

所以,为什么?

命名空间std有多个isupper函数。一个是在中定义的int std::isupper(int),另一个是在中定义的template <typename charT> bool isupper( charT ch, const locale& loc )

看来你的还包括,并且使编译器无法推断出使用了哪个isupper。您可以尝试以下操作:

return std::any_of(str.begin(), str.end(), static_cast<int (*)(int)>(std::isupper));
但是,正如其他人提到的,您最好使用lambda来包装对std::isupper的调用:
return std::any_of(str.begin(), str.end(), [](unsigned char c) { return std::isupper(c); });

最新更新