Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to effectively debug constexpr functions?

In C++14 we get upgraded version of constexpr meaning that now it will be possible to use loops, if-statements and switches. Recursion is already possible as in C++11.

I understand that constexpr functions/code should be quite simple, but still the question arise: how to effectively debug it?

Even in "The C++ Programming Language, 4th Edition" there is a sentence that debugging can be hard.

like image 640
fen Avatar asked Jan 07 '14 08:01

fen


People also ask

Does constexpr improve performance?

Using constexpr to Improve Security, Performance and Encapsulation in C++ constexpr is a new C++11 keyword that rids you of the need to create macros and hardcoded literals. It also guarantees, under certain conditions, that objects undergo static initialization.

Is constexpr guaranteed?

A constexpr function that is eligible to be evaluated at compile-time will only be evaluated at compile-time if the return value is used where a constant expression is required. Otherwise, compile-time evaluation is not guaranteed.

Are constexpr functions evaluated at compile time?

A constexpr function is one whose return value is computable at compile time when consuming code requires it. Consuming code requires the return value at compile time to initialize a constexpr variable, or to provide a non-type template argument.


1 Answers

There are two important aspects for debugging constexpr functions.

1) Make sure they compute the correct result

Here you can use regular unit-testing, asserts or a runtime debugger to step through your code. There is nothing new compared to testing regular functions here.

2) Make sure they can be evaluated at compile-time

This can be tested by evaluating the function as the right-hand side of a constexpr variable assignment.

constexpr auto my_var = my_fun(my_arg);

In order for this to work, my_fun can a) only have compile-time constant expression as actual arguments. I.e. my_arg is a literal (builtin or user-defined) or a previously computed constexpr variable or a template parameter, etc, and b) it can only call constexpr functions in its implementation (so no virtuals, no lambda expressions, etc.).

Note: it is very hard to actually debug the compiler's implementation of code generation during the compile-time evaluation of your constexpr function. You would have to attach a debugger to your compiler and actually be able to interpret the code path. Maybe some future version of Clang will let you do this, but this is not feasible with current technology.

Fortunately, because you can decouple the runtime and compile-time behavior of constexpr functions, debugging them isn't half as hard as debugging template metaprograms (which can only be run at compile-time).

like image 71
TemplateRex Avatar answered Oct 04 '22 19:10

TemplateRex