问题描述
(本示例中未使用#include,在带有g ++选项-O0 -g3 -Wall -c -fmessage-length = 0的MacOS10.14,Eclipse IDE上编译)
(No #include's were used for this example, compiled on MacOS10.14, Eclipse IDE, with g++, options -O0 -g3 -Wall -c -fmessage-length=0)
假设此变量声明:
int (*fun)(int);
无法通过"std :: toupper和std :: tolower的无效重载"进行编译.
This fails to compile with "invalid overload of std::toupper and std::tolower".
fun = (1 ? std::toupper : std::tolower); // ERROR, invalid overload
这样编译就可以了:
if (1) {
fun = std::toupper; // OK
}
else {
fun = std::tolower; // OK
}
推荐答案
std::toupper
( 1 和 2 )和std::tolower
( 1 和 2 )已超载.在为条件运算符确定它们之间的通用类型时(在分配之前到chr2fun
),无法确定应使用的重载.
std::toupper
(1 and 2) and std::tolower
(1 and 2) are overloaded. When determining the common type between them for the conditional operator (before the assignment to chr2fun
), which overloading should be used can't be determined.
您可以使用 static_cast
来指定应考虑的哪一个. (通常,首先要强制执行过载解析,确定常见类型消失了.)
You can use static_cast
to specify which one should be considered. (Presicely, to force the overload resolution happens at first respectively, then the trouble in determining the common type disappears.)
例如
chr2fun = (str2modus == STR2UP ? static_cast<int(*)(int)>(std::toupper)
: static_cast<int(*)(int)>(std::tolower));
对于第二种情况,直接分配chr2fun
; chr2fun
的类型是明确的,并且可以在过载解析.
For the 2nd case, chr2fun
is assigned directly; the type of chr2fun
is explicit and the correct overloading would be selected in overload resolution.
(重点是我的)
这篇关于为什么在直接分配而不使用条件运算符分配时,此函数指针分配起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!