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

时间:2022-09-10 09:38:45

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(),此编译器不可用。

1 个解决方案

#1


4  

In 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的静态断言所使用的那些),但它们现在只是历史上的兴趣。

#1


4  

In 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的静态断言所使用的那些),但它们现在只是历史上的兴趣。