std::transform() and toupper(), no matching function(std::transform() 和 toupper(),没有匹配的函数)
问题描述
我尝试了这个问题中的代码 C++ std::transform() 和 toupper() ..为什么会失败?
I tried the code from this question C++ std::transform() and toupper() ..why does this fail?
#include <iostream>
#include <algorithm>
int main() {
std::string s="hello";
std::string out;
std::transform(s.begin(), s.end(), std::back_inserter(out), std::toupper);
std::cout << "hello in upper case: " << out << std::endl;
}
理论上它应该可以工作,因为它是 Josuttis 书中的示例之一,但它无法编译 http://ideone.com/aYnfv.
Theoretically it should've worked as it's one of the examples in Josuttis' book, but it doesn't compile http://ideone.com/aYnfv.
海湾合作委员会为什么抱怨:
Why did GCC complain:
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::char_traits<char>, std::allocator<char> > >,
std::back_insert_iterator<std::basic_string
<char, std::char_traits<char>, std::allocator<char> > >,
<unresolved overloaded function type>)’
我在这里遗漏了什么吗?是 GCC 相关的问题吗?
Am I missing something here? Is it GCC related problem?
推荐答案
只需使用 ::toupper 而不是 std::toupper.也就是说,toupper 定义在全局命名空间中,而不是在 std 命名空间中定义的.
Just use ::toupper instead of std::toupper. That is, toupper defined in the global namespace, instead of the one defined in std namespace.
std::transform(s.begin(), s.end(), std::back_inserter(out), ::toupper);
它的工作原理:http://ideone.com/XURh7
您的代码不工作的原因:在名称空间 std 中有另一个重载函数 toupper 导致解析名称时出现问题,因为编译器无法决定当您简单地传递 std::toupper 时,您指的是哪个重载.这就是为什么编译器在错误消息中说unresolved重载函数类型,这表明存在重载.
Reason why your code is not working : there is another overloaded function toupper in the namespace std which is causing problem when resolving the name, because compiler is unable to decide which overload you're referring to, when you simply pass std::toupper. That is why the compiler is saying unresolved overloaded function type in the error message, which indicates the presence of overload(s).
因此,为了帮助编译器解析正确的重载,您必须将 std::toupper 转换为
So to help the compiler in resolving to the correct overload, you've to cast std::toupper as
(int (*)(int))std::toupper
也就是说,以下方法可行:
That is, the following would work:
//see the last argument, how it is casted to appropriate type
std::transform(s.begin(), s.end(), std::back_inserter(out),(int (*)(int))std::toupper);
自己检查一下:http://ideone.com/8A6iV
这篇关于std::transform() 和 toupper(),没有匹配的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::transform() 和 toupper(),没有匹配的函数
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
