In my previous question I wanted to use static_assert to restrict a template parameter to be a specific subtype. The question was answered, the code for archieving that is as follows:
template <typename T>
struct X {
static_assert(std::is_base_of<Y,T>::value,"T must be derived from Y!");
};
Now, I want to make the error message more concise. I.e., I want to state which type is violating this constraint. E.g., if class A
is not derived from Y
and someone instanciates X<A>
, then the error message should print "The type parameter must be derived from Y, but A isn't".
Is this somehow achievable with the standard library?
I see two challenges:
static_assert is a keyword defined in the <assert. h> header. It is available in the C11 version of C. static_assert is used to ensure that a condition is true when the code is compiled. The condition must be a constant expression.
If the condition is true, the static_assert declaration has no effect. If the condition is false, the assertion fails, the compiler displays the message in string_literal parameter and the compilation fails with an error.
Answer: Static_assert is evaluated at compile time as against the assert () statement that is evaluated at run time. Static_assert has been incorporated in C++ from C++11 onwards. It takes the conditional expression and a message to be displayed as arguments.
You cannot do this. static_assert
wants a string literal. You have no way to assemble the semantic identity of T
and Y
into the string literal.
You can hope that the compiler gives an easy to read backtrace of the template instantiation stack and gives you the value of T
and Y
template parameters of the enclosing class template instantiation.
Other people thought about this too, see http://comments.gmane.org/gmane.comp.compilers.clang.devel/5073 for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With