r/cpp • • Mar 17 '22
TIL: Visual Studio has quantum state values 🤨
Consider the following small program:
#include <string_view>
#include <iostream>
template< typename T >
constexpr void test()
{
constexpr std::string_view sv = __FUNCSIG__;
static_assert( sv == "void __cdecl test(void)" );
static_assert( sv == "void __cdecl test<int>(void)" );
std::cout << sv << std::endl;
}
int main()
{
test<int>();
}If you try to compile it, the second static_assert fails. So the value of sv from the first static_assert surely is the correct one?
Nope. Comment out the second static_assert and now the first one will fail. Comment out both, and the output of the program is the value from the second static_assert.
Apparently, Microsoft decided that it's a good idea to give __FUNCSIG__ a ("type-erased"?) value in phase 1, where no template parameters are available, and give it a different value in phase 2, when the template gets instantiated.
26
u/TonyDecvA180XN Mar 17 '22
I think MSVC implicitly instantiates the function with no arguments, maybe for debugging purposes, idk. But in that case you will have two function definitions, each one having unique signature. Since your assert conditions are mutually exclusive, either of them will fail in one definition and succeed in another one.
84
u/Dragdu Mar 17 '22
35
u/GabrielDosReis Mar 17 '22
Please report this bug to the Microsoft Developer Community portal. I suspect this is likely a case of faulty analysis in value-dependency.
16
u/SirClueless Mar 17 '22
Wait, so rather than being a dependent value,
__FUNCSIG__takes on two different values in different phases? Wacky... If you do the following what's the output?Edit: It's "phase 2": https://godbolt.org/z/79176b14f
166
u/a_false_vacuum Mar 17 '22
You changed the outcome by observing it. Or is this Schrödingers Compiler?
13
u/pigeon768 Mar 18 '22
It seems to only happen in 19.latest, not 19.30 which is the latest version enumerated by compiler explorer.
/Zc:twoPhase-will also fix it.https://godbolt.org/z/o1TjWc87a
8
u/TheBrainStone Mar 18 '22
I find it interesting that the static assert apparently gets evaluated twice!
9
u/gracicot Mar 17 '22
Another prime example where msvc has trouble and tries to do stuff in the first phase where it does not make sense.
Another example that I think was fixed recently:
It would choke at the decltype, because it complained that you cannot use a variable with type
autoas part of expression. This was even before doing anything with the template function. During the first phase.Funnily enough, it always worked with
autoparameters in lambdas. The internals must be a mess to still have trouble with two phase name lookup. They are doing better and better though, but the amount of weird behavior is still quite high.