3

I got some code sent to me today, and it's using the std::transform on a std::string to make it all lowercase. The sender had written and compiled the code in Visual Studio 2010:

using namespace std;
string test = "TEST";
transform(test.begin(), test.end(), test.begin(), tolower);

Wheras I compiled it on OSx with GCC and/or Clang, and got compile error, as it involves namespace's clashing.

There is indeed a bunch of answered questions that addresses the global namespace vs local (::tolower vs std::tolower), but this is regarding the fact that this piece of code actually works on VS.

Questions I'd like answers to:

  1. Why does Visual Studio compile this?
  2. How come it defaults (?) to the global namespace :: when std:: should take precedence?

Note: Im using GCC 4.2 and Clang (425.0.24 LLVM 3.2svn) on OSx Mountain Lion

hugolm84
  • 166
  • 1
  • 5

1 Answers1

1

The problem here is two-fold. First, if you don't specifically #include <cctype>, you might be getting a tolower that's a macro, not a function (though I don't know whether this is actually a problem these days and whether this would break standards compliance.)

Second, in C++ tolower is overloaded. You need to select a specific overload to use:

transform(test2.begin(), test2.end(), test2.begin(),
          static_cast<int(*)(int)>(tolower));

But I don't know the reason why std:: gets an overloaded version and :: does not. In any event, I'd recommend that you stay away from those C functions and instead use std::ctype from the <locale> header, which provides a better tolower:

http://www.cplusplus.com/reference/locale/ctype

Nikos C.
  • 50,738
  • 9
  • 71
  • 96
  • While this answers parts of the question, its still interesting to understand why VS takes ::tolower before (or should I say rather than) std::tolower. There might be some argument lookup, [link](http://msdn.microsoft.com/en-us/library/60bx1ys7(v=vs.90).aspx) taking place. But im not sure, as I dont have a VS instance installed. Note that GCC also has argument dependant lookup, but exhibits different behaviour in this case. – hugolm84 Feb 22 '13 at 13:10