简体   繁体   English

如何在C ++中强制编译错误?

[英]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: 我想这样做有几个原因:

  • to force compilation to fail while I'm working on new features which haven't been implemented yet. 在我正在开发尚未实现的新功能时强制编译失败。 (compile time ! TODO reminder) (编译时间!TODO提醒)
  • to create a more readable error when attempting to implement an unsupported template specialization. 尝试实现不受支持的模板特化时创建更可读的错误。

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.

相关问题 如何处理 C++ 中的指针赋值编译错误(错误:没有可行的重载“=”) - How can I deal with pointer assignment compile error (error: no viable overloaded "=") in C++ 如何在C / C ++中强制删除锁定的文件? - How can I force the deletion of locked files in C/C++? 我可以强制C ++类使用最少的空间进行编译吗? - Can I force a C++ class to compile using the minimum amount of space? 如何通过C ++宏调用编译时错误? - How can I invoke a compile-time error via a C++ macro? 我如何在c ++上构建glib-生成.cpp时发生编译错误 - How can I build glib at c++ - compile error when build .cpp 如何通过编译错误找到C ++拷贝构造函数的用途? - how can I find where a C++ copy constructor is being USED via a compile error? 如果有人在C ++中调用方法,则强制发生错误(编译时) - Force error (compile time) if anyone calls a method in C++ 如何在c ++中强制符号作为符号引用(以编程方式) - How can I force symbol a symbol reference in c++ (programmatically) 如何在MSBuild中强制使用C ++平台? - How can I force the C++ platform in MSBuild? 如何解决此c ++类型列表模板编译错误? - how do I fix this c++ typelist template compile error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM