Why does the following code compile with MSVC++?
-
12-12-2019 - |
Вопрос
struct X{};
template<class T>
decltype(X() == int()) f(T const&){ return true; }
int main(void) {
X x;
f(x);
}
Why, just why? There is no operator==
defined anywhere!
I really want to understand what's going on here, to provide a detailed bug report on MS Connect. My journey to insanity began around here in the Lounge<C++> chat room...
(Note: Neither GCC nor Clang accept this code.)
Oh, and btw, adding a private X(int)
ctor causes the compilation to fail:
struct X{
X(){}
private:
X(int);
};
template<class T>
decltype(X() == int()) f(T const&){ return true; }
int main(void) {
X x;
f(x);
}
Output:
1>src\main.cpp(12): error C2248: 'X::X' : cannot access private member declared in class 'X'
1> src\main.cpp(4) : see declaration of 'X::X'
1> src\main.cpp(1) : see declaration of 'X'
Решение
What version of MS VC++ are you using?
For whatever it may be worth, VC++11 Beta rejects your code with:
trash.cpp(8): error C2893: Failed to specialize function template ''unknown-type' f(const T &)'
With the following template arguments:
'X'
I'm not sure that's what I'd call the most helpful or informative error message ever, but it is rejecting the code.
Under the circumstances, I'd guess filing a bug report is probably going to accomplish little (if anything). The response I'd expect would be essentially: "Already fixed in VC++11. Upgrade when you can."