c++ - 为什么这个函数指针赋值在直接赋值而不是使用条件运算符时起作用?

标签 c++ function pointers overloading

(此示例未使用 #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(12)和 std::tolower(12)被重载。在为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种情况,直接赋值chr2funchr2fun 的类型是显式的,将在 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/

相关文章:

c++ - 如何在 C++ 中模拟 5 级流水线?

c - 在 C 中的 vector 函数序列中避免(初学者)分配错误

javascript - 停止 javascript/jquery 中的函数执行

c - C中变量的逻辑内存地址

c++ - Lua中看起来像table的函数有哪些?

c++ - 如何使用标准库函数通过错误检查将字符串 (char*) 转换为数字?

C++如何检查N个对象中的一些对象是否相等

javascript - 为什么我的自定义 jQuery 函数不起作用?

c - 函数中的双指针取消引用

c++ - 有人能解释一下这段 C++ 代码吗,我看不懂