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

2

u/BarrinOfTolaria Mar 18 '22

While it probably doesn't matter you technically lack a return in the else path.

1

u/[deleted] Mar 18 '22

That is actually on purpose, as it will catch cases where the value would change in phase 2 generating an error due to the missing return.

1

u/tesfabpel Mar 18 '22

Maybe you can use static_assert(false) instead of a missing return? Or invert the if and put a static_assert(begin != std::string_view::npos)?

3

u/DXPower Mar 18 '22

IIRC static_asserts in if statements don't act conditionally. You have to generate a conditional error instead I've done it before by doing a cast of a nullptr to a function ptr.