Jump to content

Featured Replies

Posted

SANDOR_DARGO_ROUND.JPGstatic_assert further evolves with C++26. Our tool for compile-time assertion will support user-generated error messages. As such, we’ll be able to reuse messages as well as enrich them with information available at compile-time making diagnostics easier to read.

C++26: user-generated static_assert messages

by Sandor Dargo

From the article:

Our first quest into the world of C++26 was about =delete with an optional error message, which improves the readability of the source code and potentially the error messages. In this next part of our journey, we will continue to focus on readability improvements, particularly those for error messages.

With C++26 and the acceptance of P2741R3, we are getting better error messages for static_assert. Compile time assertions were introduced in C++11 with a mandatory message. Since C++17, the message is only optional. And with C++26, static_assert evolves further and the message can be a constant expression instead of an unevaluated string. In other words, it can have some dynamic elements.

This was not the first attempt to make such a feature part of C++, but back in 2014, when something similar was proposed, C++ didnΓÇÖt have enough compile-time programming capabilities to make this easily implementable.

Why is this change useful?

Before looking at some concrete examples of utilisation, letΓÇÖs dig into the motivations behind this feature.

Obviously, we want better error messages. C++ is infamous for its horrendous error logs when the compilation fails. Even though we must admit that itΓÇÖs more and more just a legacy, the situation improved a lot over the course of the years. In any case, it was mostly template-related error messages that were behind the biggest issues.

While compile-time assertions with their custom messages already meant an improvement, user-generated diagnostic messages will further improve the situation.

But thatΓÇÖs not the only motivation. Sometimes you donΓÇÖt want different, or better messages. You just want the same message in several assertions without having to duplicate it. Without this change, the following piece of code doesnΓÇÖt compile:

View the full article

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

Recently Browsing 0

  • No registered users viewing this page.