什么在这里与cctype?

Mar*_*ork 14 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 ;
}
Run Code Online (Sandbox Code Playgroud)

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

namespace std
{
  // Other similar `using` deleted for brevity.
  using ::toupper;
}
Run Code Online (Sandbox Code Playgroud)

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

std::transform(s.begin(),s.end(), std::back_inserter(S), std::toupper);
Run Code Online (Sandbox Code Playgroud)

我现在希望现在也可以编译.但是我收到编译错误:

kk.cpp:12:错误:没有匹配函数来调用`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 >>>,< 未解析的重载函数类型 >)'

其中手动编辑也解决了:

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>)'
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

GMa*_*ckG 11

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

std::transform(s.begin(),s.end(), std::back_inserter(S),
                (int(&)(int))std::toupper);
Run Code Online (Sandbox Code Playgroud)

  • @Nawaz:是的,从导入`:: toupper`和`<locale>`:`template <typename C> C toupper(C c,const locale&l);`.只指定`std :: toupper`对参数无效,因为它可能是.通过铸造,它消除了一个过载. (2认同)