【问题标题】:Why can not pass "std" prefix when giving Predicate parameter为什么给 Predicate 参数时不能传递“std”前缀
【发布时间】:2020-02-18 08:08:04
【问题描述】:

我有这个代码:

#include <cctype>
#include <algorithm>

int main()
{
    std::string str("ABCD");
    std::all_of(str.begin(), str.end(), ::isxdigit);
    return 0;
}

std::all_of 需要一个谓词作为最后一个参数。我要传递的是std::isxdigit。当我将它作为::isxdigit 传递时,它工作正常,但是当我使用std 传递它时,比如std::isxdigit,我得到了这个错误 :

12:58: error: no matching function for call to 'all_of(std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved overloaded function type>)'
12:58: note: candidate is:
In file included from /usr/include/c++/4.9/algorithm:62:0,
                 from 6:
/usr/include/c++/4.9/bits/stl_algo.h:508:5: note: template<class _IIter, class _Predicate> bool std::all_of(_IIter, _IIter, _Predicate)
     all_of(_InputIterator __first, _InputIterator __last, _Predicate __pred)
     ^
/usr/include/c++/4.9/bits/stl_algo.h:508:5: note:   template argument deduction/substitution failed:
12:58: note:   couldn't deduce template parameter '_Predicate'

为什么会出现此错误? 如果它是标准的,那么用 std 前缀传递它有什么问题?

【问题讨论】:

标签: c++ c++11 std


【解决方案1】:

为了使它与std::isxdigit 一起工作,您应该编写如下内容:

#include <cctype>
#include <string>
#include <algorithm>

int main()
{
    std::string str("ABCD");
    std::all_of(str.begin(), str.end(), [](unsigned char c){ return std::isxdigit(c); });
    return 0;
}

Demo

【讨论】:

  • 它还应该使代码更快 - 否则 isxdigit 将被视为模板内的函数指针,这可能导致无法优化的代码缓慢。
猜你喜欢
  • 2021-07-18
  • 1970-01-01
  • 2021-10-10
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多