C++ Logo

std-discussion

Advanced search

Can static_assert(false) be ignored in if constexpr?

From: Yongwei Wu <wuyongwei_at_[hidden]>
Date: Wed, 13 Jan 2021 22:07:05 +0800
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,

-- 
Yongwei Wu
URL: http://wyw.dcweb.cn/

Received on 2021-01-13 08:07:22