我正在尝试使用Qt Creator 2.0.1编译以下程序:
void f()
{
string a = "abc";
transform(a.begin(), a.end(), a.begin(), ptr_fun(tolower));
}
Run Code Online (Sandbox Code Playgroud)
mingw抛出以下错误:
调用ptr_fun没有匹配函数(<unresolved overloaded function type>)
使用VC++ 2010 Express可以很好地编译该函数.mingw有什么问题?
谢谢.
问题是功能模板引入的歧义
template <class charT> charT tolower(charT c, const locale& loc);
Run Code Online (Sandbox Code Playgroud)
我猜mingw <locale>间接包含了你的程序包含的一个头文件,而VC++没有.
您可以通过使用强制转换消除歧义来解决此问题tolower:
typedef int (*foo)(int);
ptr_fun((foo)tolower);
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望维护程序员向您扔鞋:
ptr_fun((int (*)(int))tolower);
Run Code Online (Sandbox Code Playgroud)
请注意,正如亚美尼亚所说,你实际上并不需要ptr_fun这里.它将一元函数转换为可适应的一元函数,但transform不需要其参数可适应.区别在于类型是否具有嵌套的typedef for argument_type和result_type.原始函数类型没有,ptr_fun返回一个类似的函子类型.
最后,在你的平台上签名if tolower上调用C一般都不安全.您的示例字符串是正常的,因为"abc"中的所有字符都不是负数,但您应该执行以下操作:charchar
char fixed_tolower(char c) {
return tolower((unsigned char)c);
}
transform(..., fixed_tolower);
Run Code Online (Sandbox Code Playgroud)
或者更好的内联机会:
struct fixed_tolower : unary_function<char, char> {
char operator()(char c) const {
return tolower((unsigned char)c);
}
};
transform(..., fixed_tolower());
Run Code Online (Sandbox Code Playgroud)
我还没有检查它是否真的对GCC产生任何影响,无论是从内联的POV还是从tolower负面数字上实际barf 的mingw实现的POV .