Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats going on here with cctype?

To my surprise the following code compiles:

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <cctype>

int main() {
   std::string s="nawaz";
   std::string S;
   std::transform(s.begin(),s.end(), std::back_inserter(S), ::toupper);
   std::cout << S ;
}

I had expected it to fail because of the ::toupper which I believed should be in the std namespace. A quick check of cctype shows that it is but it is imported from the root namesapce (Mystery solved there).

namespace std
{
  // Other similar `using` deleted for brevity.
  using ::toupper;
}

So first problem solved but if I change the transform() line above too:

std::transform(s.begin(),s.end(), std::back_inserter(S), std::toupper);

I would now expect this to now also compile. But I get a compiler error:

kk.cpp:12: 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::cha r_traits<char>, std::allocator<char> > >, std::back_insert_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unresolved overloaded function type>)'

Which with manual editing resolved too:

kk.cpp:12: error: no matching function for call to
         `transform(iterator<std::string>,
                    iterator<std::string>,
                    std::back_insert_iterator<std::string>,
                    <unresolved overloaded function type>)'

What am I missing?

like image 957
Martin York Avatar asked Mar 23 '11 18:03

Martin York


1 Answers

It doesn't work because there are overloads of std::toupper. You can fix it by casting to your desired function overload:

std::transform(s.begin(),s.end(), std::back_inserter(S),
                (int(&)(int))std::toupper);
like image 81
GManNickG Avatar answered Sep 28 '22 17:09

GManNickG