Variable iterating on itself – different behavior with different types

Please see edits below! For Each edits also added below under Edit2 More edits about ForEach and Collections at Edit3 One last edit about ForEach and Collections at Edit4 A final note about iteration behavior at Edit5 Part of the subtlety of this odd behavior in the semantics of variant evaluation when used as a … Read more

How to make a safer C++ variant visitor, similar to switch statements?

If you want to only allow a subset of types, then you can use a static_assert at the beginning of the lambda, e.g.: template <typename T, typename… Args> struct is_one_of: std::disjunction<std::is_same<std::decay_t<T>, Args>…> {}; std::visit([](auto&& arg) { static_assert(is_one_of<decltype(arg), int, long, double, std::string>{}, “Non matching type.”); using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, int>) std::cout << “int … Read more

How is duck typing different from the old ‘variant’ type and/or interfaces?

In some of the answers here, I’ve seen some incorrect use of terminology, which has lead people to provide wrong answers. So, before I give my answer, I’m going to provide a few definitions: Strongly typed A language is strongly typed if it enforces the type safety of a program. That means that it guarantees … Read more