Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make my C++ compiler emit a constexpr value (e.g. in warning?)

(This is sort of an XY problem, but bear with me.)

I'm getting this compilation warning about a shift amount being too large. Now, to diagnose this, I would like my compiler to somehow emit the constexpr value which is used as a shift amount.

The way I've done it so far is try to instantiate a type with a numeric parameter which I know I can place out of range, then add the constexpr value I wanted and get an error which shows me the sum. But that's an ugly hack. Is there a way to get constexpr values (hopefully not only integers) to be emitted to the standard error stream? e.g. together with some explanatory text or a warning message?

I'm asking about GCC 6.x and later and clang 4.x and later.

like image 677
einpoklum Avatar asked Oct 29 '22 21:10

einpoklum


1 Answers

Well, the obvious approach is similar to what you said -- make the compiler mention the value while emitting a diagnostic.

constexpr int I = 8 % 3;

template<int i>
class TheValueYouWantIs { static_assert(i != i); };


int main() {
    TheValueYouWantIs<I>();
}

Thus:

prog.cpp: In instantiation of ‘class TheValueYouWantIs<2>’:
prog.cpp:8:27:   required from here
[...less informative stuff...]

Warnings are obviously more compiler-dependent, but should be easily possible. This sort of thing won't help you with char arrays, though. Not a complete solution.

like image 133
Sneftel Avatar answered Nov 14 '22 13:11

Sneftel