“未解析的重载函数类型"尝试在 C++ 中将 for_each 与迭代器和函数一起使用

2022-01-10 00:00:00 iterator g++ c++
//for( unsigned int i=0; i < c.size(); i++ ) tolower( c[i] );
for_each( c.begin(), c.end(), tolower );

我正在尝试使用 for_each 循环代替 for 循环进行赋值.

I am trying to use a for_each loop in place of the for loop for an assignment.

我不确定为什么会收到此错误消息:

I am unsure why I am getting this error message:

In function avoid clean_entry(const std::string&, std::string&)a:
prog4.cc:62:40: error: no matching function for call to afor_each(std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved   overloaded function type>)a

推荐答案

写:

for_each( c.begin(), c.end(), ::tolower );

或者:

for_each( c.begin(), c.end(), (int(*)(int))tolower);

我已经多次遇到这个问题,以至于我厌倦了在我的代码以及其他人的代码中解决这个问题.

I've faced this problem so many times that I'm tired of fixing this in my code, as well as in others' code.

您的代码不工作的原因:命名空间 std 中有另一个重载函数 tolower 导致解析名称时出现问题,因为编译器无法当您简单地传递 tolower 1 时,决定您指的是哪个重载.这就是为什么编译器在错误消息中说 unresolved 重载函数类型,这表明存在重载.

Reason why your code is not working : there is another overloaded function tolower in the namespace std which is causing problem when resolving the name, because the compiler is unable to decide which overload you're referring to, when you simply pass tolower 1. That is why the compiler is saying unresolved overloaded function type in the error message, which indicates the presence of overload(s).

因此,为了帮助编译器解决正确的重载问题,您必须将 tolower 强制转换为

So to help the compiler in resolving to the correct overload, you've to cast tolower as

(int (*)(int))tolower

然后编译器得到提示选择全局 tolower 函数,在其他方面,可以通过编写 ::tolower 来使用.

then the compiler gets the hint to select the global tolower function, which in other ways, can be used by writing ::tolower.

1.我猜您已经在代码中编写了 using namespace std .我也建议你不要这样做.一般使用完全限定名称.

1. I guess you've written using namespace std in your code. I would also suggest you to not to do that. Use fully-qualified names in general.

顺便说一句,我认为您想将输入字符串转换为小写,如果是这样,那么 std::for_each 不会这样做.你必须使用 std::transform 函数作为:

By the way, I think you want to transform the input string into lower case, if so, then std::for_each wouldn't do that. You've to use std::transform function as:

std::string out;
std::transform(c.begin(), c.end(), std::back_inserter(out), ::tolower);
//out is output here. it's lowercase string.

相关文章