I would like to create a compile-time error in my C++ code with a custom error message. I want to do this for a couple of reasons:
I'm sure there is a trick to doing this but I cant find a resource explaining the method. I would wrap the code in a #define of the form COMPILE_FAIL("error message");
Thanks D
Compilation error refers to a state when a compiler fails to compile a piece of computer program source code, either due to errors in the code, or, more unusually, due to errors in the compiler itself. A compilation error message often helps programmers debugging the source code.
A compile error happens when the compiler reports something wrong with your program, and does not produce a machine-language translation. You will get compile errors.
Compilers emit both erorrs, which prevent your code from compiling at all, and warnings, which indicate a potential problem, but still let your code compile. (Unless you have ask the compiler to treat warnings as errors, such as with the -Werror flag to gcc).
The directive ' #error ' causes the preprocessor to report a fatal error. The tokens forming the rest of the line following ' #error ' are used as the error message. The directive ' #warning ' is like ' #error ', but causes the preprocessor to issue a warning and continue preprocessing.
Use #error
:
#error "YOUR MESSAGE"
This produces an error from the preprocessor. If you want to detect an error at a later stage (e.g. during template processing), use static_assert
(a C++11 feature).
Look into static_assert
.
Example:
#include <iostream>
#include <type_traits>
template<typename T>
class matrix {
static_assert(std::is_integral<T>::value, "Can only be integral type");
};
int main() {
matrix<int*> v; //error: static assertion failed: Can only be integral type
}
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