条件运算符无法解析重载的成员函数指针

条件运算符无法解析重载的成员函数指针

本文介绍了条件运算符无法解析重载的成员函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在处理C ++中重载成员函数的指针时遇到了一个小问题。以下代码可以正常编译:

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

大概这与编译器将条件运算符的返回值与函数指针类型?我可以解决这个问题,但是我很想知道规范说明所有这些事情应该起作用,因为这似乎有点不直观,并且是否有解决此问题的方法而不会退回到5行if-then-else

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.

我正在使用MSVC ++,如果有什么区别。

I'm using MSVC++, if that makes any difference.

谢谢!

推荐答案

从13.4 / 1节开始(重载函数的地址,[over.over]):

From section 13.4/1 ("Address of overloaded function," [over.over]):


  • 正在初始化的对象或引用(8.5、8.5.3),

  • 分配的左侧(5.17),

  • 函数的参数(5.2.2),

  • 用户的参数-定义的运算符(13.5),

  • 函数,运算符或转换的返回值(6.6.3)或

  • 显式类型转换(5.2.3、5.2.9、5.4)。

  • an object or reference being initialized (8.5, 8.5.3),
  • the left side of an assignment (5.17),
  • a parameter of a function (5.2.2),
  • a parameter of a user-defined operator (13.5),
  • the return value of a function, operator function, or conversion (6.6.3), or
  • an explicit type conversion (5.2.3, 5.2.9, 5.4).

重载函数名称可以以& 运算符。在没有列出的上下文中,没有参数的情况下,不能使用重载的函数名。 [注意:忽略重载的函数名周围的任何多余的括号集(5.1)。 ]

The overload function name can be preceded by the & operator. An overloaded function name shall not be used without arguments in contexts other than those listed. [Note: any redundant set of parentheses surrounding the overloaded function name is ignored (5.1). ]

您希望从上面的列表中选择的 target 是第一个对象正在初始化。但是有一种条件运算符,条件运算符是根据操作数而不是任何目标类型来确定其类型的。

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.

由于显式类型转换已包含在目标,您可以分别在条件表达式中类型转换每个成员指针表达式。我先做一个typedef:

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:

typedef void (Foo::* float_func)(const float);
float_func func = (someCondition ? float_func(&Foo::X) : float_func(&Foo::Y));

这篇关于条件运算符无法解析重载的成员函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 11:59