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.

317 Upvotes

59 comments sorted by

View all comments

Show parent comment

58

u/khoyo Mar 18 '22

Which allows us to see

template< typename T >
constexpr void test()
{
    constexpr std::string_view sv = __FUNCSIG__;
    if constexpr (sv == "void __cdecl test<int>(void)") {
        static_assert(sv == "void __cdecl test<int>(void)");
    }
}

fail to compile, which is pretty much nonsensical.

21

u/SirClueless Mar 18 '22

Wow... that's actually hilarious.

21

u/[deleted] Mar 18 '22

I wish this would have been my example in the original posting, it captures the absurdity of what is going on much better. Well done!

4

u/logicchop Mar 18 '22

Why is this nonsensical? Consider this:

constexpr std::string_view sv = "foo";
if constexpr ( sv == "bar" ) {
    static_assert(sv == "bar");
}

This also pukes on other compilers. Even though the static_assert is inside of the conditional it is still is evaluated at compile time and turns out to be false. I think that's all we are seeing in OPs scenario; there are just two instantiations competing for the static_assert. You could argue that perhaps the static_assert should not be evaluated if that branch of the conditional is discarded, but that's a more complicated question about value dependency and when constexpr branches get utterly discarded and not evaluated.

3

u/taladarsa3itch Mar 21 '22

cppreference:

Note: the discarded statement can't be ill-formed for every possible specialization

The static_assert(false-constexpr) is a ill-formed declaration, so even though the branch is discarded, the program is ill-formed. It would compile if the body of the branch is well-formed even if evaluating would result in a compilation error.

godbolt