C++ – no matching function for call to ‘transform

c++

can anyone tell me what is the mistake 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."

Best Solution

There are two functions with name toupper. One from cctype header:

int toupper( int ch );

And second from locale header:

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

Compiler can't deduce which function should be used, since you allow namespace std. You should use scope resolution operator(::) to choose function defined in global space:

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

Or, better: Do not use using namespace std.


Thanks to @Praetorian -

This is probably the cause of the error, but adding :: may not always work. If you include cctype toupper is not guaranteed to exist in the global namespace. A cast can provide the necessary disambiguation static_cast<int(*)(int)>(std::toupper)

So, the call should look like:

std::transform
(
    str.begin(), str.end(),
    str.begin(),
    static_cast<int(*)(int)>(std::toupper)
);
Related Question