C++ C++;如果函数不能计数';推断模板

C++ C++;如果函数不能计数';推断模板,c++,C++,我试图使用C++的count\u if函数来查看std::string中有多少十六进制数字。当我尝试以下方法时: string s = "123abc"; cout << count_if(s.begin(), s.end(), isxdigit) << endl; string s=“123abc”; CUT< P>在C标准库(头 ,C++等效头>代码> >中有一个函数 int xxDigiint(int)。如果,可以在count\u中明确使用此选项 如果包含,则此

我试图使用C++的
count\u if
函数来查看
std::string
中有多少十六进制数字。当我尝试以下方法时:

string s = "123abc";
cout << count_if(s.begin(), s.end(), isxdigit) << endl;
string s=“123abc”;

CUT< P>在C标准库(头<代码> <代码>,C++等效头>代码> <代码> >中有一个函数<代码> int xxDigiint(int)<代码>。如果
,可以在
count\u中明确使用此选项

如果包含
,则此函数将在全局命名空间中结束。如果包含
,则保证将其放在命名空间
std
;但是,由于它是一个C库函数,所以C++标准库(实现)也允许将其放入全局命名空间。

另一方面,C++标准库(头<代码> <代码>)中有一个函数模板<代码> ixDigie<代码>。这只放在命名空间

std


出现此错误的原因是,您可能有一个
使用名称空间std在某个地方,或者使
中的
std::isxdigit
可见。然后,名称
isxdigit
表示一组重载函数。由于存在多个候选对象,并且如果
接受了其中的许多候选对象,那么编译器现在无法计算您所指的重载

例如,您可以通过使用
static\u cast(&isxdigit)
指定所指的重载


使用
::isxdigit
时,只会找到一个函数,因此编译器知道它的类型并可以推断模板参数


与手动选择重载相比,更有用的解决方案是使用具有通用函数调用运算符的函数对象:

struct Isxdigit
{
    template<class T>
    bool operator()(T const& p) const
    {
        using std::isxdigit;
        return isxdigit(p);
    }
};

int main()
{
    string s = "123abc";
    cout << count_if(s.begin(), s.end(), Isxdigit()) << endl;
}
struct Isxdigit
{
模板
布尔运算符()(T常量和p常量)
{
使用std::isxdigit;
返回值为xdigit(p);
}
};
int main()
{
字符串s=“123abc”;
库特
struct Isxdigit
{
    template<class T>
    bool operator()(T const& p) const
    {
        using std::isxdigit;
        return isxdigit(p);
    }
};

int main()
{
    string s = "123abc";
    cout << count_if(s.begin(), s.end(), Isxdigit()) << endl;
}
int main()
{
    string s = "123abc";
    cout << count_if(s.begin(), s.end(), [](auto p){ return isxdigit(p); })
         << endl;
}