Zorglub29
Zorglub29

Reputation: 8841

Macro to raise compiler error for string literal C++

I know of the (evil?) C++ macro that raises a compiler error on all but string literal (found it in SO some time ago but cannot find it again):

#define IS_STRING_LITERAL(X) "" X ""

Is there a macro that can do the 'opposite', ie raise a compiler error on a string literal, but not on other inputs?

Edit: see comment, this is for debug macros on microcontroller. String literals should live in flash, I want to be notified at compiler time if I call the wrong macro. 'Others' should be int, float, char, char [] and other 'basic' type.

Upvotes: 1

Views: 279

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96236

Depends what those 'other inputs' are. If they can be anything, then the answer is probably 'impossible'.

You could do something like this:

#define foo(x) (std::enable_if_t<!std::is_same_v<const char *, decltype(+(x))>>(), (x))

This line checks if x is const char * (or decays to one) and raises a error if it's true. (It's not what you asked for: it's impossible to pass a plain const char [] into it.)

std::cout << foo(123); // Works.
std::cout << foo("123"); // error: no type named 'type' in 'struct std::enable_if<false, void>'

Upvotes: 1

Related Questions