获取指向在命名空间中声明的函数的指针

Get pointer to function declared into namespace

本文关键字:声明 函数 指针 命名空间 取指 获取      更新时间:2023-10-16

我想计算std::string中的空格。对于std::count_if来说非常简单的任务所以我写了下面的代码:

std::cout<<std::count_if(str.cbegin(), str.cend(), &std::isspace);

…编译错误(xcode): No matching function for call to 'count_if'

我改成:

std::cout<<std::count_if(str.cbegin(), str.cend(), &isspace);

编译错误已经不在了

你能解释一下第一行有什么问题吗?当函数在命名空间中获得函数指针时,我是否错过了一些东西?这是否与ADL相关,因为isspacecount_if来自相同的名称空间?

编辑:

完整构建日志:

应用程序/xcode/内容/开发/工具链/XcodeDefault.xctoolchain/usr/lib/c++/v1/算法:1097:1:候选模板被忽略:无法推断模板参数"_Predicate"

错误与包含(顺序和/或存在)有关。

有两个std::isspace函数,一个接受单个参数,另一个接受2个参数。第一个在<cctype>中声明,第二个在<locale>中声明。

int isspace ( int c );

template <class charT>
  bool isspace (charT c, const locale& loc);

通常,在c++ 11中,计数可以写成

std::count_if(str.cbegin(), str.cend(), [](char c) {
  return std::isspace(c, std::locale());
});