From: Jonathan Wakely Date: Tue, 18 Jun 2024 15:59:52 +0000 (+0100) Subject: libstdc++: Make std::any_cast ill-formed (LWG 3305) X-Git-Tag: basepoints/gcc-16~8015 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=466ee78e3e975627440992dac67973ee314a0551;p=thirdparty%2Fgcc.git libstdc++: Make std::any_cast ill-formed (LWG 3305) LWG 3305 was approved earlier this year in Tokyo. We need to give an error if using std::any_cast, but std::any_cast is valid (but always returns null). libstdc++-v3/ChangeLog: * include/std/any (any_cast(any*), any_cast(const any*)): Add static assertion to reject void types, as per LWG 3305. * testsuite/20_util/any/misc/lwg3305.cc: New test. --- diff --git a/libstdc++-v3/include/std/any b/libstdc++-v3/include/std/any index 690ddc2aa574..e4709b1ce046 100644 --- a/libstdc++-v3/include/std/any +++ b/libstdc++-v3/include/std/any @@ -554,6 +554,12 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION template inline const _ValueType* any_cast(const any* __any) noexcept { + // _GLIBCXX_RESOLVE_LIB_DEFECTS + // 3305. any_cast + static_assert(!is_void_v<_ValueType>); + + // As an optimization, don't bother instantiating __any_caster for + // function types, since std::any can only hold objects. if constexpr (is_object_v<_ValueType>) if (__any) return static_cast<_ValueType*>(__any_caster<_ValueType>(__any)); @@ -563,6 +569,8 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION template inline _ValueType* any_cast(any* __any) noexcept { + static_assert(!is_void_v<_ValueType>); + if constexpr (is_object_v<_ValueType>) if (__any) return static_cast<_ValueType*>(__any_caster<_ValueType>(__any)); diff --git a/libstdc++-v3/testsuite/20_util/any/misc/lwg3305.cc b/libstdc++-v3/testsuite/20_util/any/misc/lwg3305.cc new file mode 100644 index 000000000000..49f5d747ab3c --- /dev/null +++ b/libstdc++-v3/testsuite/20_util/any/misc/lwg3305.cc @@ -0,0 +1,15 @@ +// { dg-do compile { target c++17 } } + +// LWG 3305. any_cast + +#include + +void +test_lwg3305() +{ + std::any a; + (void) std::any_cast(&a); // { dg-error "here" } + const std::any a2; + (void) std::any_cast(&a2); // { dg-error "here" } +} +// { dg-error "static assertion failed" "" { target *-*-* } 0 }