令我惊讶的是,以下代码可以编译:
#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/