C++中错误no matching function for call to transform

博客介绍了使用transform函数将字符串转为大写时,传入toupper出现编译错误的问题。指出Linux中将toupper实现为宏而非函数是报错原因,并给出四种解决方法,包括明确命名空间、重写函数、强制转换及使用LAMBDA表达式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

将str转为大写

编译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:

/* Note: this is decimal, not hex, to avoid accidental promotion to unsigned */
#define _toupper(__c) ((__c) & ~32)
#define _tolower(__c) ((__c) | 32)

__ctype_inline int toupper(int __c)
{
return islower(__c) ? _toupper(__c) : __c;
}

__ctype_inline int tolower(int __c)
{
return isupper(__c) ? _tolower(__c) : __c;
}

有三种解决方法:

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

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

2.自己重写一个函数

inline char charToUpper(char c)
{
return std::toupper(c);
}

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

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

4.补充。LAMBDA表达式

transform(str.begin(), str.end(), str.begin(), [](int c) {return toupper(c); });

 

原文:https://blog.youkuaiyun.com/winting_qiqi/article/details/21397211

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值