Best way to fake static_assert inside if constexpr?

60 views Asked by At

As you may know static_assert does not care about if it is inside "active" branch of if constexpr(it always "runs").

I have a hack workaround that uses invalid array dimensions to trigger the error, but it is ugly. Are there better solutions in C++20?

// does not work
template<typename T>
void argh(){
    if constexpr(sizeof (T)<123456 ) {

    } else {
        static_assert(0);
    }
}
// works but confusing to novice programmers, both code and error
template<typename T>
void meh(){
    if constexpr(sizeof (T)<123456 ) {

    } else {
        int error_triggering[-sizeof(T)];
    }
}
0

There are 0 answers