C++ Logo

std-proposals

Advanced search

Re: std::is_constexpr_constructible (/ std::is_constexpr)

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Sat, 23 Oct 2021 13:41:03 +0100
On Sat, 23 Oct 2021 at 08:28, Michael Scire via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> I find myself somewhat often wanting to have function behavior differ
> depending on whether or not an action can be performed at compiletime or
> not.
>
> I needed to implement this recently and found it very, very hard to do so.
> The language doesn't seem to expose any clean way to detect whether an
> action can be performed at compile-time without a compile-error in the
> false case.
>

I may be missing something, but couldn't you write something like:

    if constexpr (requires { typename std::bool_constant<(T(args...), void
(), true)>; })

or, avoiding the library,

    if constexpr (requires { []<int>(){}.template operator()<(T(args...),
void(), 0)>(); })

Demo: https://godbolt.org/z/4hv9xToMo

(I'm not convinced the template keyword is required in the latter case, but
gcc crashes without it, so.)

Noting of course that to be potentially usable in constexpr (or constinit)
initialization the args must be themselves constant expressions, so when
encapsulating this in a helper function you'd need to pass the arguments by
template:

template<class T, auto... args>
inline constexpr bool is_constexpr_constructible_v =
requires { []<int>(){}.template operator()<(T(args...), void(), 0)>(); };

Cheers,
Ed

Received on 2021-10-23 07:41:17