C++ Logo

std-proposals

Advanced search

Re: [std-proposals] noexcept has gotten a bit hairy -- I want a compiler error

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Tue, 29 Apr 2025 10:38:02 +0100
On Tue, Apr 29, 2025 at 2:14 AM Thiago Macieira via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Now try strchr.


Maybe something like this:

    #include <utility> // forward

    namespace std {

        template<typename T>
        struct make_memfuncptr_noexcept {
            static_assert( nullptr == "The type T must be a const
member function pointer" );
        };

        template<bool b, typename R, typename Class, typename... Params>
        struct make_memfuncptr_noexcept< R(Class::* const)(Params...)
const noexcept(b) > {
            using type = R (Class::* const)(Params...) const noexcept;
        };

        template<typename Lambda, typename... Params>
        decltype(auto) wont_throw(Lambda &&f, Params&&... args) noexcept
        {
            auto const mfp = &Lambda::template operator()<Params...>;
            using FuncPtrNoExcept = typename
make_memfuncptr_noexcept<decltype(mfp)>::type;
            auto const mfpne =
*static_cast<FuncPtrNoExcept*>(static_cast<void const*>(&mfp));
            return (f.*mfpne)( forward<Params>(args)... );
        }
    }

    #define WONT_THROW(f, ...)
               \
        std::wont_throw(
               \
            [&](auto&&... args) noexcept(false) -> decltype(auto)
               \
            {
               \
                return f(std::forward<decltype(args)>(args)...);
               \
            },
               \
            __VA_ARGS__ )


    // ================ Now here comes the test code:

    #include <cstring> // strchr

    void const *Func(char const *const p) noexcept
    {
        return WONT_THROW(std::strchr, p, 'r');
    }

    int main(int const argc, char **const argv)
    {
        return nullptr == Func( argv[0] );
    }

Here's the GodBolt: https://godbolt.org/z/81384xo6r

Received on 2025-04-29 09:38:09