织梦CMS - 轻松建站从此开始!

罗索

C++常见错误之:no matching function for call to transform

落鹤生 发布于 2012-07-14 21:59 点击:次 
C++常见错误之:no matching function for call to ‘transform(__gnu_cxx::__normal_iterator, std::allocator > >, __gnu_cxx::__normal_iterator, std::allocator > >, __gnu_cxx::__normal_iterator, std::allocator > >, )’
TAG:

初学C++哈,不知道这个错误是不是很silly,高手轻拍。情况如下:

  1. #include <string> 
  2. #include <algorithm> 
  3. using namespace std; 
  4.  
  5. int main (int argc, char * const argv[]){ 
  6.   string str = "Hello"
  7.   transform(str.begin(), str.end(), str.begin(), toupper); 
  8.   cout << str << endl; 
  9.   
  10.   return 0; 

程序的意思很简单,去把Hello都转换为大写。

编译死活不通过:

$ g++ -g -Wall strToUpper.cpp -o strToUpper
strToUpper.cpp: In function ‘int main(int, char* const*)’:
strToUpper.cpp:9: error: no matching function for call to ‘transform(__gnu_cxx::__normal_iterator, std::allocator > >, __gnu_cxx::__normal_iterator, std::allocator > >, __gnu_cxx::__normal_iterator, std::allocator > >, )’

后来查明原因如下——

我们先看看这个函数的定义:

template   OutIter transform(InIter start, InIter end, OutIter result, Func unaryFunc)

它要求参数和返回值都要是char。Linux中将toupper实现为一个宏而不是函数:
/usr/lib/syslinux/com32/include/ctype.h:

  1. /* Note: this is decimal, not hex, to avoid
  2.  accidental promotion to unsigned */ 
  3. #define _toupper(__c) ((__c) & ~32) 
  4. #define _tolower(__c) ((__c) | 32) 
  5.  
  6. __ctype_inline int toupper(int __c) 
  7. return islower(__c) ? _toupper(__c) : __c; 
  8.  
  9. __ctype_inline int tolower(int __c) 
  10. return isupper(__c) ? _tolower(__c) : __c; 

有三种解决方法:

1.因为在全局命名空间中有实现的函数(而不是宏),所以我们明确命名空间,这并不是总奏效,但是在我的g++环境中没有问题:

  1. transform(str.begin(), str.end(), str.begin(), ::toupper); 

2.自己写一个函数出来—wraper

  1. inline char charToUpper(char c) 
  2.     return std::toupper(c); 

3.强制转化:将toupper转换为一个返回值为int,参数只有一个int的函数指针。

  1. transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper); 

 

(秩名)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201207/16155.html]
本文出处:2cto 作者:秩名
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容