There is no corresponding function to call 'transform

can someone tell me what is a bug in this program

#include <iostream> #include <algorithm> using namespace std; int main() { string str = "Now"; transform(str.begin(), str.end(), str.begin(), toupper); cout<<str; return 0; } 

Error:

 "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> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unresolved overloaded function type>)' compilation terminated due to -Wfatal-errors." 
+4
source share
3 answers

There are two functions called toupper . One of the cctype header:

 int toupper( int ch ); 

And the second from the locale header:

 charT toupper( charT ch, const locale& loc ); 

The compiler cannot determine which function should be used because you are resolving the std . You must use the region resolution operator ( :: :) to select a function defined in global space:

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

Or, better: do not use using namespace std .


Thanks @Praetorian -

This is probably the cause of the error, but adding :: may not always work. If you included cctype toupper in the global namespace. Casting can provide the required value static_cast<int(*)(int)>(std::toupper)

So, the call should look like this:

 std::transform ( str.begin(), str.end(), str.begin(), static_cast<int(*)(int)>(std::toupper) ); 
+9
source

To use toupper , you need to include the header file:

 #include <cctype> 

You also need to include the header file:

 #include <string> 

The problem is that std::toupper accepts int as a parameter, and std::transform passes the char to the function, so it has a problem (kindly provided by @juanchopanza).

You can try:

  #include <functional> std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper)); 

See sample code from std :: transform

Or you can implement your own toupper , which takes a char as an argument.

+2
source

As the compiler buried in his error message, the real problem is that toupper is an overloaded function, and the compiler cannot determine which one you want. There C function toupper (int), which may or may not be a macro (may not be in C ++, but does the C library support it?), And there std :: toupper (char, locale) from (is drawn in without a doubt), which you provided globally with using namespace std; .

Tony's solution works because it accidentally solved the overload problem with its separate function.

0
source

Source: https://habr.com/ru/post/1483153/


All Articles