问题
struct A
{
enum InnerEnum { X };
A(InnerEnum x)
{}
};
int main()
{
A a(X);
}
The compiler complains: error C2065: 'X' : undeclared identifier
The compiler knows what the constructor's parameter type is, so when I pass X as the argument, the compiler should know it is a valid argument.
I know this is not ADL(Argument-dependent Name Lookup, also known as Koenig Lookup), but I think it's useful and pretty handy. Because I don't have to write as follows:
A a(A::X);
I think the ADL rule should be generalized to such a case.
Am I right?
回答1:
Function calls in C++ are subject to function overload resolution. Overload resolution is driven by the argument types. I.e. the language "works" specifically in that direction: from argument types to specific version of the function with the given name.
You are proposing to introduce a reverse process - argument type deduction based on function name. This will not work in general case. It might work in cases when there's only one candidate function (as in your example), but, again, in is contrary to principles that work in the general situation when the function is overloaded.
Of course, the situation will get even more complicated when name lookup on unqualified name X
can see something else named X
in addition to your A::X
. I think it can easily get very counterintuitive.
回答2:
I think the ADL rule should be generalized to such a case.
No thank you.
C++ has its share of (nasty) surprises (which other language do you know requires explicit
as a keyword?), and I don't see enough merit in your example to add to this list of unexpected language rules hindering my code in unexpected situations.
If you find the additional typing entailed in class-name followed by the two colons as too much effort, then surely the general baroque nature of C++ syntax should have put you off by now?
来源:https://stackoverflow.com/questions/14163667/why-does-c11-not-support-name-lookup-like-this