參考:http://forums.codeguru.com/showthread.php?489969-no-matching-function-transform
這裡介紹了 C++ STL string 大小寫轉換的代碼,但是要注意,可能有些機器用下面的代碼編譯不過
#include <cctype> // toupper, tolower
#include <iostream>
#include <string>
#include <algorithm> // transform
using namespace std;
int main()
{
string str = "[email protected]";
transform(str.begin(), str.end(), str.begin(), toupper);
cout << str << endl;
transform(str.begin(), str.end(), str.begin(), tolower);
cout << str << endl;
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> > >, <unknown type>)’
這裡 說明了原因:
The problem is that the version of std::tolower inherited from the C standard library is a non-template function, but there are other versions of std::tolower that are function templates, and it is possible for them to be included depending on the standard library implementation. You actually want to use the non-template function, but there is ambiguity when just tolower is provided as the predicate.
翻譯過來就是說,既有C版本的toupper/tolower函數,又有STL模闆函數toupper/tolower,二者存在沖突。
解決辦法:
在toupper/tolower前面加::,強制指定是C版本的(這時也不要include <cctype>了):
#include <iostream>
#include <string>
#include <algorithm> // transform
using namespace std;
int main()
{
string str = "[email protected]";
transform(str.begin(), str.end(), str.begin(), ::toupper);
cout << str << endl;
transform(str.begin(), str.end(), str.begin(), ::tolower);
cout << str << endl;
return 0;
}