2

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.

Walter
  • 44,150
  • 20
  • 113
  • 196

1 Answers1

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Hmm. That assumes that the macro is expanded in a context where `static_assert()` is allowed. – Walter Mar 14 '14 at 16:03
  • 1
    @Walter: `static_assert` is treated as a declaration, and allowed (just about) anywhere. – Mike Seymour Mar 14 '14 at 16:04
  • In contexts where an expression is expected it can be useful to wrap static_assert() in a block, e.g. #define UNUSABLE_VALUE { _Static_assert (false, "bad value"); }. This is maybe only a good idea in contexts where the clients are known, e.g. when the macro is a tuple designed for consumption by known other macros. – Britton Kerin Mar 30 '20 at 21:42