Home > Enterprise >  Why does MSVC not complain about the expression `i.str()` where `i` is an `int`?
Why does MSVC not complain about the expression `i.str()` where `i` is an `int`?

Time:08-22

I got some ill-formed code like the following, but it builds with MSVC 19.32.31329 and /std:c latest.

#include <Windows.h>

template<typename T>
void foo() {
    int i;
    // Can be anything that looks like a function call
    baz(i.str());
}

int WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
    int i;
    // The following line is wrong because i has an integral type
    // and doesn't have .str().
    i.str();
}

The code is clearly wrong and shouldn't compile, but it does. Is this a compiler bug?

CodePudding user response:

Yes, this is a compiler bug that was apparently introduced in version 19.32. It can be observed when compiling either with /std:c latest or /std:c 20.

It appears that anything that's inside a function template can trick MSVC into learning new rules about integral types. As illustrated in the question once the compiler is through parsing foo it will subsequently allow any expression exp that has type int (or is implicitly convertible to it) to have its (fantasy) member str() invoked.

A bug report has been issued (see this answer).

CodePudding user response:

This seems to be a msvc bug. The program is ill-formed as i is a built in type and not a class type so that i.str() is invalid.

Note also that with msvc the program does not compiles in C 17 but compiles in C 20. Demo.


A bug report for the same has been submitted as:

The call someint.str() compiles when invalid function template is present

  • Related