Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSVC bug in fold expression using variant?

Consider following code:

#include <variant>

class A {};
class B {};

template<typename... Ts, typename Variant>
bool constexpr is_of(const Variant& variant)
{
  return std::visit(
      [](const auto& v) {
        using V = std::decay_t<decltype(v)>;
        return (std::is_same_v<V, Ts> || ...);
      },
      variant);
}


int main()
{
  using Variant = std::variant<A, B>;
  static_assert(is_of<A>(Variant{A{}}));
  static_assert(!is_of<B>(Variant{A{}}));

  static_assert(is_of<B>(Variant{B{}}));  // Fails
  static_assert(!is_of<A>(Variant{B{}}));  // Fails
  
  static_assert(!is_of<int>(Variant{A{}}));
  static_assert(!is_of<int>(Variant{B{}}));
  return 0;
}

is_of is a function which returns whether the value in a variant matches a range of types.

Why do the two static_asserts fail? GCC and clang behave as expected.

I was not able to reduce the example even more. The visit and the fold expression seem to be crucial, when I expand it using if constexpr, it works as expected.

https://godbolt.org/z/Wbd3GPzbc

like image 687
pasbi Avatar asked May 03 '26 06:05

pasbi


1 Answers

Yes, it was a bug in MSVC, which is fixed in Visual Studio 2022 version 17.12, where all static_asserts in your program are accepted.

See https://developercommunity.visualstudio.com/t/Wrong-evaluation-of-fold-expression-insi/10730639

like image 76
Fedor Avatar answered May 05 '26 19:05

Fedor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!