C++ Logo

std-discussion

Advanced search

Re: Can static_assert(false) be ignored in if constexpr?

From: Daniel Krügler <daniel.kruegler_at_[hidden]>
Date: Wed, 13 Jan 2021 15:23:46 +0100
Am Mi., 13. Jan. 2021 um 15:07 Uhr schrieb Yongwei Wu via
Std-Discussion <std-discussion_at_[hidden]>:
>
> I have tried writing code like the following:
>
> template <typename T>
> ReturnType Function(T&& arg)
> {
> if constexpr(condition_on_<T>) {
> // Something to do
> } else if constexpr(another_condition_on<T>) {
> // Something else to do
> } else {
> static_assert(false, "T does not satisfy constraint");
> }
>
> // Some common processing regarding arg
> }
>
> Yet, even if the provided T goes to one of the first two constexpr condition branches, the static assertion will fail....
>
> Yes, I can rewrite the code above as:
>
> template <typename T>
> ReturnType Function(T&& arg)
> {
> static_assert(condition_on<T> && another_condition_on<T>);
> if constexpr(condition_on_<T>) {
> // Something to do
> } else {
> // Something else to do
> }
> }
>
> But then I have the conditions duplicated. Code duplications are bad, right?
>
> So my question is: Is there a reason that the static_assert(false) in an unused if-constexpr branch must cause the whole compilation to fail? Is there a way to achieve what I want without code duplications?
>
> Thanks in advance.
>
> Best regards,
>

A possible solution would be to write an always_false<T> class or
variable template or concept and use it where you currently use
"false". The relevant part is that the "false" value is dependent.

- Daniel

Received on 2021-01-13 08:24:01