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!
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).
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.
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: