How to easily static_assert(false)
in else{}
of if constexpr
?
#include <type_traits>
#include <iostream>
class B{};
class C{};
class D{};
template<class T> void complexIf(){
if constexpr(std::is_same_v<T,B>){
//^ actually it is some complex statement
std::cout<<"1"<<std::endl;
}else if constexpr(std::is_same_v<T,C>){
//^ another uber complex thingy
std::cout<<"2"<<std::endl;
}
//another 4-5 "else if constexpr(){}"
else{//#1
static_assert(false);
}
};
int main(){
complexIf<B>();// should compliable
//complexIf<D>() should uncompliable
}
The above MCVE isn't compilable.
The reason was explained in constexpr if and static_assert .
( That question is more of a language-lawyer one. )
In this question, I would like to know an elegant workaround.
My poor solutions
The first workaround (copy-paste condition to #1
) :-
else{//#1
static_assert(std::is_same_v<T,B> &&std::is_same_v<T,C> );
//^ a ton of copy-paste condition
}
^ It is less maintainable + dirty.
My second attempt (cache as constexpr bool
):-
template<class T> void complexIf(){
constexpr bool case1=std::is_same_v<T,B>;
constexpr bool case2=std::is_same_v<T,C>;
if constexpr(case1){
//^ actually it is some complex statement
std::cout<<"1"<<std::endl;
}else if constexpr(case2){
//^ another uber complex thingy
std::cout<<"2"<<std::endl;
}
//another 4-5 "else if constexpr(){}"
else{//#1
static_assert(case1&case2 );
}
}
^ It is less clear and quite confusing.
In real world, complexIf
is a function to manage custom smart pointers.
Each if constexpr
is mostly about checking type of the pointers.