Today, we need to implement a function to convert lower-case letters to upper-case letters. Because the input parameter is a string class in SL, the first idea is to use the Transform Algorithm to implement this function, but an error is returned. After returning home, I wrote the following test code to see where the error was and how to solve it.
# Include <iostream>
# Include <algorithm>
# Include <cctype>
Using namespace STD;
Int main (INT argc, char * argv [])
{
String S ("Hello World ");
Transform (S. Begin (), S. End (), S. Begin (), toupper );
Cout <S <Endl;
Return 0;
}
The following is the error message of G ++:
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 >>,< unknown type> )'
From the red part, we can see that the touppe function is considered an unknown function. However, when I pull out the toupper function independently for testing, the compilation is successful. That is to say, this function is okay. So what is the problem?
After wandering around the Internet, I finally found the cause:
A touppe function is reloaded in the standard library, while GCC is fully loaded by the C library, but glibc does not. Therefore, G ++ considers this function to be ambiguous during compilation. The following are two toupper functions in the Standard Library:
Int Std: toupper (INT); // from <cctype>
Template <class chart>
Chart STD: toupper (chart, const locale &); // from <locale>
The problem is identified, but there is always a solution. Since the error is due to ambiguity, you only need to eliminate the ambiguity.
1. intervene in the packaging function
This is the simplest method, because there is only one packaging function. As long as you specify the function to be used in the packaging function, ambiguity will naturally disappear. Take toupper as an example, we can use the following packaging function:
Int toupper (int c)
{
Return toupper (C );
}
2. Forced conversion: Convert toupper to an int value. The parameter has only one int function pointer:
STD: Transform (S. Begin (), S. End (), S. Begin (), (INT (*) (INT) toupper );
3. In GCC, toupper is implemented as a macro rather than a function, but there are implemented functions (rather than macros) in the global namespace. Therefore, it is not always effective to clarify the namespace, but there is no problem in my g ++ environment:
Transform (S. Begin (), S. End (), S. Begin (),: toupper );