[英]How can I force a compile error in C++?
I would like to create a compile-time error in my C++ code with a custom error message. 我想在我的C ++代码中使用自定义错误消息创建编译时错误。 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");
我将代码包装在COMPILE_FAIL形式的#define中(“错误消息”);
Thanks D 感谢:D
Use #error
: 使用
#error
:
#error "YOUR MESSAGE"
This produces an error from the preprocessor. 这会从预处理器产生错误。 If you want to detect an error at a later stage (eg during template processing), use
static_assert
(a C++11 feature). 如果要在稍后阶段检测错误(例如在模板处理期间),请使用
static_assert
(C ++ 11功能)。
Look into static_assert
. 查看
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
}
强制编译错误(GCC,Clang样式):
#error "You ain't finished this yet!"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.