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

时间:2022-03-19 01:11:54

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:

我想在我的C ++代码中使用自定义错误消息创建编译时错误。我想这样做有几个原因:

  • 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

3 个解决方案

#1


35  

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).

这会从预处理器产生错误。如果要在稍后阶段检测错误(例如在模板处理期间),请使用static_assert(C ++ 11功能)。

#2


18  

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
}

#3


5  

To force a compiler error (GCC, Clang style):

强制编译错误(GCC,Clang样式):

#error "You ain't finished this yet!"

#1


35  

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).

这会从预处理器产生错误。如果要在稍后阶段检测错误(例如在模板处理期间),请使用static_assert(C ++ 11功能)。

#2


18  

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
}

#3


5  

To force a compiler error (GCC, Clang style):

强制编译错误(GCC,Clang样式):

#error "You ain't finished this yet!"