简体   繁体   English

如何通过C ++宏调用编译时错误?

[英]How can I invoke a compile-time error via a C++ macro?

The idea is to cause a compile-time error with an error message if a certain macro is invoked . 这个想法是如果调用了某个宏,则会导致编译时错误和错误消息。 Can this be done? 能做到吗? How? 怎么样?

#ifdef RUBBISH_COMPILER
#  define alignof(T)  // what here?
#endif

const std::size_t = alignof(some_type);  // invocation, causing compilation error

The invocation shall produce a sensible error message like alignof() not available with this compiler . 调用将产生一个明智的错误消息,例如alignof()在此编译器中不可用

In C++11, 在C ++ 11中,

#define DONT_INVOKE_ME static_assert(false, "Don't invoke this macro");

Historically, it was easy to cause an error, but trickier to get a message into the output. 从历史上看,很容易造成错误,但要使消息进入输出则比较棘手。 One simple trick was to create an invalid declaration, with the message in the declared name: 一个简单的技巧是创建一个无效的声明,并以声明的名称显示消息:

#define DONT_INVOKE_ME char dont_invoke_this_macro[-1];

This isn't perfect, as you can't use freeform text for the message - it must be a valid identifier. 这不是完美的,因为您不能对消息使用自由格式的文本-它必须是有效的标识符。 There were fancier tricks (such as those used by Boost's static assert), but they're only of historical interest these days. 有一些更奇妙的把戏(例如,Boost的静态断言所使用的把戏),但是这些天这些东西仅具有历史意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM