首页 > 解决方案 > 带有谓词 isalpha 的 C++ find_if 给出错误

问题描述

我不明白为什么我有这个错误,显然 isalpha 函数被重新声明了两次(我的编辑器标记我:“2个重载”)但我不明白为什么,这是我的代码:

#include <iostream>
#include <set>
#include <algorithm>
#include <ctype.h>
#include <string>
using namespace std;

int main(){
    cin.tie(nullptr);ios_base::sync_with_stdio(false);
    string line;
    string::iterator prev, act;
    while(cin>>line){
        // act = find_if(line.begin(), line.end(), [](int x) {return isalpha(x);}); // GOOD
        act = find_if(line.begin(), line.end(), isalpha); // ERROR
        cout<<*act<<endl; 
    }
}

我使用 g++ (MinGW.org GCC-6.3.0-1) 6.3.0

错误:

1215.cpp: In function 'int main()':
1215.cpp:14:56: error: no matching function for call to 'find_if(std::__cxx11::basic_string<char>::iterator, std::__cxx11::basic_string<char>::iterator, <unresolved overloaded function type>)'
         act = find_if(line.begin(), line.end(), isalpha); // ERROR
                                                        ^
In file included from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\algorithm:62:0,
                 from 1215.cpp:3:
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\stl_algo.h:3808:5: note: candidate: template<class _IIter, class _Predicate> _IIter std::find_if(_IIter, _IIter, _Predicate)
     find_if(_InputIterator __first, _InputIterator __last,
     ^~~~~~~
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\bits\stl_algo.h:3808:5: note:   template argument deduction/substitution failed:
1215.cpp:14:56: note:   couldn't deduce template parameter '_Predicate'
         act = find_if(line.begin(), line.end(), isalpha); // ERROR

注意:如果我不使用“使用命名空间标准”,代码会正确编译和执行。

提前感谢您的任何答案或建议

标签: c++std

解决方案


这就是可能发生的事情。

命名空间下的标头中有一个isalpha()同一个命名空间下的标中有另一个。将两者都拉入您的范围,从而在推导模板时产生歧义。<cctype> stdisalpha()<locale> stdusing namespace std

故事的寓意:避免使用 using namespace std.


推荐阅读