条件运算符无法解析重载的成员函数指针
我在处理 C++ 中重载成员函数的指针时遇到了一个小问题。以下代码可以正常编译:
class Foo {
public:
float X() const;
void X(const float x);
float Y() const;
void Y(const float y);
};
void (Foo::*func)(const float) = &Foo::X;
但这无法编译(编译器抱怨重载不明确):
void (Foo::*func)(const float) = (someCondition ? &Foo::X : &Foo::Y);
大概这与编译器将条件运算符的返回值与函数指针类型分开排序有关?我可以解决这个问题,但我很想知道规范是如何规定所有这些应该工作的,因为它看起来有点不直观,以及是否有某种方法可以解决它而不会退回到 5 行 if-then-else 。
我正在使用 MSVC++,如果这有什么区别的话。
谢谢!
I'm having a minor issue dealing with pointers to overloaded member functions in C++. The following code compiles fine:
class Foo {
public:
float X() const;
void X(const float x);
float Y() const;
void Y(const float y);
};
void (Foo::*func)(const float) = &Foo::X;
But this doesn't compile (the compiler complains that the overloads are ambiguous):
void (Foo::*func)(const float) = (someCondition ? &Foo::X : &Foo::Y);
Presumably this is something to do with the compiler sorting out the return value of the conditional operator separately from the function pointer type? I can work around it, but I'm interested to know how the spec says all this is supposed to work since it seems a little unintuitive and if there's some way to work around it without falling back to 5 lines of if-then-else.
I'm using MSVC++, if that makes any difference.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从第 13.4/1 节(“重载函数的地址”[over.over]):
您希望从上面的列表中选择的目标是第一个,一个正在初始化的对象。但是有一个条件运算符阻碍了这一过程,条件运算符根据其操作数而不是任何目标类型来确定其类型。
由于显式类型转换包含在目标列表中,因此您可以单独对条件表达式中的每个成员指针表达式进行类型转换。我首先创建一个 typedef:
From section 13.4/1 ("Address of overloaded function," [over.over]):
The target you were hoping would be selected from the above list was the first one, an object being initialized. But there's a conditional operator in the way, and conditional operators determine their types from their operands, not from any target type.
Since explicit type conversions are included in the list of targets, you can type-cast each member-pointer expression in the conditional expression separately. I'd make a typedef first:
尝试:
问题是三元运算符的结果类型由其参数确定。
在这种情况下,它无法确定结果类型,因为输入类型有多个选项。直到三元运算符的类型确定后,它才会尝试赋值。
Try:
The problem is the result type of the operator trinary is determined by its arguments.
In this situation it can not determine the result type because the input types has multuiple options. It is not until the type of the trinary operator has been determined that it will attempt the assignment.
示例:
您需要立即强制转换 &Foo::X 才能解决重载问题。请注意,如果您注释掉重载的 float X(),则不需要这样做。
编译器似乎不够智能,无法推断三元表达式所需的返回类型(这可能是一个错误)。
Example:
You need to cast &Foo::X immediately in order to resolve the overload. Note that if you comment out the overloaded float X(), you don't need to do so.
It looks like the compiler isn't smart enough to infer the required return type of a ternary expression (this may be a bug).