为什么在直接分配而不使用条件运算符分配时,此函数指针分配起作用? [英] Why does this function pointer assignment work when assigned directly but not with the conditional operator?

查看:107
本文介绍了为什么在直接分配而不使用条件运算符分配时,此函数指针分配起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(本示例中未使用#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( 2 )和std::tolower( 1 条件运算符确定它们之间的通用类型时(在分配之前到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.)

static_cast还可以通过执行到特定类型的函数到指针的转换来消除函数重载的歧义

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));

对于第二种情况,直接分配chr2funchr2fun的类型是明确的,并且可以在过载解析.

For the 2nd case, chr2fun is assigned directly; the type of chr2fun is explicit and the correct overloading would be selected in 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.

这篇关于为什么在直接分配而不使用条件运算符分配时,此函数指针分配起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆