(此示例未使用 #include,在 MacOS10.14、Eclipse IDE 上编译,使用 g++,选项 -O0 -g3 -Wall -c -fmessage-length=0)
假设这个变量声明:
int (*fun)(int);
编译失败,“std::toupper 和 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)被重载。在为conditional operator确定它们之间的共同类型时(在分配给 chr2fun
之前),无法确定应该使用哪个重载。
您可以使用 static_cast
指定应考虑哪一个。 (确切地说,强制 overload resolution 分别发生,然后确定普通类型的麻烦就消失了。)
static_cast
may also be used to disambiguate function overloads by performing a function-to-pointer conversion to specific type
例如
chr2fun = (str2modus == STR2UP ? static_cast<int(*)(int)>(std::toupper)
: static_cast<int(*)(int)>(std::tolower));
对于第2种情况,直接赋值chr2fun
; chr2fun
的类型是显式的,将在 overload resolution 中选择正确的重载.
(强调我的)
In all these contexts, the function selected from the overload set is the function whose type matches the pointer to function, reference to function, or pointer to member function type that is expected by target: the object or reference being initialized, the left-hand side of the assignment, function or operator parameter, the return type of a function, the target type of a cast, or the type of the template parameter, respectively.
关于c++ - 为什么这个函数指针赋值在直接赋值而不是使用条件运算符时起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56884194/