c++ - cctype 是怎么回事?

标签 c++ namespaces std

令我惊讶的是,以下代码可以编译:

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <cctype>

int main() {
   std::string s="nawaz";
   std::string S;
   std::transform(s.begin(),s.end(), std::back_inserter(S), ::toupper);
   std::cout << S ;
}

我原以为它会失败,因为我认为 ::toupper 应该在 std 命名空间中。快速检查 cctype 显示它是,但它是从根 namespace 导入的(在那里解决了谜题)。

namespace std
{
  // Other similar `using` deleted for brevity.
  using ::toupper;
}

所以第一个问题解决了,但是如果我也更改上面的 transform() 行:

std::transform(s.begin(),s.end(), std::back_inserter(S), std::toupper);

我现在希望它现在也可以编译。但我得到一个编译器错误:

kk.cpp:12: error: no matching function for call to `transform(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::cha r_traits<char>, std::allocator<char> > >, std::back_insert_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unresolved overloaded function type>)'

手动编辑也解决了:

kk.cpp:12: error: no matching function for call to
         `transform(iterator<std::string>,
                    iterator<std::string>,
                    std::back_insert_iterator<std::string>,
                    <unresolved overloaded function type>)'

我错过了什么?

最佳答案

它不起作用,因为有 std::toupper 的重载。您可以通过强制转换为所需的函数重载来修复它:

std::transform(s.begin(),s.end(), std::back_inserter(S),
                (int(&)(int))std::toupper);

关于c++ - cctype 是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5409791/

相关文章:

c++ - C++ 中的单词语言检测

c++ - 调试使用调试标志运行的代码和使用 opt 标志运行的段错误

C++ std::fill 和 std::fill_n 错误 "error C2679"

c++ std::getline/std::sort 没有按预期工作

c++ - 创建 vector 的问题

c++ - boost 几何/空间查询形状

node.js - 套接字 : Namespace & WS protocol

c++ - 命名空间和前向声明问题

python - 如何避免在调用函数时重新输入长变量名

Android ndk std::to_string 支持