fosstodon.org is one of the many independent Mastodon servers you can use to participate in the fediverse.
Fosstodon is an invite only Mastodon instance that is open to those who are interested in technology; particularly free & open source software. If you wish to join, contact us for an invite.

Administered by:

Server stats:

9.8K
active users

#constexpr

2 posts2 participants0 posts today

Apparently, #C++ developers are so smitten with `constexpr` that they're willing to sacrifice their first-born to it in #C++26. 🤷‍♂️ Gone are the days of simple "Hello, World" — now it's all about wrangling `constexpr` lambdas while hoping the compiler gods smile upon you. 😅
sandordargo.com/blog/2025/04/2 #constexpr #programming #humor #developercommunity #HackerNews #ngated

Sandor Dargo’s Blog · C++26: more constexpr in the core languageSince constexpr was added to the language in C++11, its scope has been gradually expanded. In the beginning, we couldn’t even use if, else or loops, which were changed in C++14. C++17 added support for constexpr lambdas. C++20 added the ability to use allocation and use std::vector and std::string in constant expressions. In this article, let’s see how constexpr evolves with C++26. To be more punctual, let’s see what language features become more constexpr-friendly. We’ll discuss library changes in a separate article, as well as constexpr exceptions, which need both language and library changes. P2738R1: constexpr cast from void* Thanks to the acceptance of P2738R1, starting from C++26, one can cast from void* to a pointer of type T in constant expressions, if the type of the object at that adress is exactly the type of T. Note that conversions to interconvertible - including pointers to base classes - or not related types are not permitted. The motivation behind this change is to make several standard library functions or types work at compile time. To name a few examples: std::format, std::function, std::function_ref, std::any. The reason why this change will allow many more for more constexpr in the standard library is that storing void* is a commonly used compilation firewall technique to reduce template instantiations and the number of symbols in compiled binaries. P2747R2: constexpr placement new As std::construct_at is a limited tool that only allows to perform value initialization but not others such as default or list initialization, there has been a need to make placement new usable in constant expressions. At the same time, placement new is a very, maybe even too flexible tool and to use it in a safe way requires casting to void* and then back to T*. This faced some issues, but the acceptance of P2738R1 and the ability of casting from void* in constant expressions made the impossible possible. If you are looking for more details, check P2747R2. P2686R5: constexpr structured bindings and references to constexpr variables This is a rather long (20 pages) proposal and I found it not particularly easy to read. That’s not the fault of the authors, the problem is hard to address. The paper which is based on another, went through 5 revisions, discusses various solutions, and lists the wording changes on more than 10 pages. Long story short, you’ll be able to declare structured bindings constexpr. As structured bindings behave like references, the same restrictions apply as to constexpr references. Those restrictions become more relaxed. Before, a constexpr reference had to bind to a variable with static storage duration, so that the address doesn’t change from one evaluation to another. With C++26, in addition, variables with automatic storage duration are also accepted if and only if the address is constant relative to the stack frame in which the reference or the structured binding lives. In practice, this means that you cannot have a constexpr reference in a lambda to bind to an enclosing function. The reason is that in order to access that variable, the expression is something like this->__x where __x represents the captured address of x. As we don’t know at compile time what object this points to, it’s not a constant expression. Conclusion In this article, we reviewed how constexpr evolves in the C++26 core language. We are getting constexpr cast from void*, placement new, structured bindings and even exceptions (not discussed today). In the next article, we’ll see how the standard library’s constexpr support evolves. Connect deeper If you liked this article, please hit on the like button, subscribe to my newsletter and let’s connect on Twitter!
Sandor Dargo’s Blog · C++26: more constexpr in the core languageSince constexpr was added to the language in C++11, its scope has been gradually expanded. In the beginning, we couldn’t even use if, else or loops, which were changed in C++14. C++17 added support for constexpr lambdas. C++20 added the ability to use allocation and use std::vector and std::string in constant expressions. In this article, let’s see how constexpr evolves with C++26. To be more punctual, let’s see what language features become more constexpr-friendly. We’ll discuss library changes in a separate article, as well as constexpr exceptions, which need both language and library changes. P2738R1: constexpr cast from void* Thanks to the acceptance of P2738R1, starting from C++26, one can cast from void* to a pointer of type T in constant expressions, if the type of the object at that adress is exactly the type of T. Note that conversions to interconvertible - including pointers to base classes - or not related types are not permitted. The motivation behind this change is to make several standard library functions or types work at compile time. To name a few examples: std::format, std::function, std::function_ref, std::any. The reason why this change will allow many more for more constexpr in the standard library is that storing void* is a commonly used compilation firewall technique to reduce template instantiations and the number of symbols in compiled binaries. P2747R2: constexpr placement new As std::construct_at is a limited tool that only allows to perform value initialization but not others such as default or list initialization, there has been a need to make placement new usable in constant expressions. At the same time, placement new is a very, maybe even too flexible tool and to use it in a safe way requires casting to void* and then back to T*. This faced some issues, but the acceptance of P2738R1 and the ability of casting from void* in constant expressions made the impossible possible. If you are looking for more details, check P2747R2. P2686R5: constexpr structured bindings and references to constexpr variables This is a rather long (20 pages) proposal and I found it not particularly easy to read. That’s not the fault of the authors, the problem is hard to address. The paper which is based on another, went through 5 revisions, discusses various solutions, and lists the wording changes on more than 10 pages. Long story short, you’ll be able to declare structured bindings constexpr. As structured bindings behave like references, the same restrictions apply as to constexpr references. Those restrictions become more relaxed. Before, a constexpr reference had to bind to a variable with static storage duration, so that the address doesn’t change from one evaluation to another. With C++26, in addition, variables with automatic storage duration are also accepted if and only if the address is constant relative to the stack frame in which the reference or the structured binding lives. In practice, this means that you cannot have a constexpr reference in a lambda to bind to an enclosing function. The reason is that in order to access that variable, the expression is something like this->__x where __x represents the captured address of x. As we don’t know at compile time what object this points to, it’s not a constant expression. Conclusion In this article, we reviewed how constexpr evolves in the C++26 core language. We are getting constexpr cast from void*, placement new, structured bindings and even exceptions (not discussed today). In the next article, we’ll see how the standard library’s constexpr support evolves. Connect deeper If you liked this article, please hit on the like button, subscribe to my newsletter and let’s connect on Twitter!

C++26 — встреча ISO в Хагенберге

В середине февраля в Хагенберге состоялась встреча международного комитета по стандартизации языка программирования C++. В этот раз прорабатывались следующие большие темы: std::hive Constexpr, ещё больше constexpr Безопасность, контракты, hardening, профили, UB и std::launder Relocate #embed Об этом и других новинках расскажу в посте

habr.com/ru/companies/yandex/a

#c++29 #с++29 #c++26 #с++26 #с++ #c++ #reflection #constexpr #exception #simd #safety #security #undefined_behavior #memory #byte #bit #contracts #relocation #hive #object_pool #embed

ХабрC++26 — встреча ISO в ХагенбергеВ середине февраля в Хагенберге состоялась встреча международного комитета по стандартизации языка программирования C++. В этот раз прорабатывались следующие большие темы: std::hive Constexpr, ещё...

ISO C++ — встреча международного комитета в Польше

В конце ноября состоялась встреча международного комитета по стандартизации языка программирования C++. В этот раз без внимания не остались темы: Рефлексия времени компиляции и оператор «монобровь» Constexpr, много constexpr SIMD Structured bindings as a pack Безопасность, контракты, libc++ hardening, профили, UB и std::launder Сколько бит в байте? Об этом и других новинках расскажу в посте

habr.com/ru/companies/yandex/a

#c++26 #с++26 #с++ #c++ #reflection #constexpr #consteval #exception #simd #safety #security #undefined_behavior #memory #byte #bit

ХабрISO C++ — встреча международного комитета в ПольшеВ конце ноября состоялась встреча международного комитета по стандартизации языка программирования C++. В этот раз без внимания не остались темы: Рефлексия времени компиляции...

Type Loopholes: решая нерешаемое. Рефлексия времени компиляции

Лупхолы — это техника, позволяющая манипулировать глобальным состоянием компилятора, добавляя значения и считывая их. Эта техника позволяет решать многие задачи, некоторые из которых будут рассмотрены в статье: Узнать, какие параметры принимает конструктор типа. Узнать, с какими шаблонными параметрами вызывался метод/функция с ADL. Как сделать метапрограммирование с типами более похожим на обычный код, где есть состояние.

habr.com/ru/articles/824574/

#лупхолы #метапрограммирование #рефлексия #c++ #constexpr

ХабрType Loopholes: решая нерешаемое. Рефлексия времени компиляцииЛупхолы — это техника, позволяющая манипулировать глобальным состоянием компилятора, добавляя значения и считывая их. Эта техника позволяет решать многие задачи, некоторые из которых будут рассмотрены...

C++26 — прогресс и новинки от ISO C++

Работа в комитете по стандартизации языка C++ активно кипит. Недавно состоялось очередное заседание. Как один из участников, поделюсь сегодня с Хабром свежими новостями и описанием изменений, которые планируются в С++26. До нового стандарта C++ остаётся чуть больше года, и вот некоторые новинки, которые попали в черновик стандарта за последние две встречи: запрет возврата из функции ссылок на временное значение, [[indeterminate]] и уменьшение количества Undefined Behavior, диагностика при =delete; , арифметика насыщения, линейная алгебра (да-да! BLAS и немного LAPACK), индексирование variadic-параметров и шаблонов ...[42] , вменяемый assert(...) , и другие приятные мелочи. Помимо этого, вас ждут планы и прогресс комитета по большим фичам и многое другое. Рассмотрим новинки на примерах

habr.com/ru/companies/yandex/a

#c++ #с++ #constexpr #c++26 #с++26 #numeric #floating_point #float #double #iso #программирование #span #functions #function #blas #lapack #atomic #linear_algebra #variadic_templates

ХабрC++26 — прогресс и новинки от ISO C++Работа в комитете по стандартизации языка C++ активно кипит. Недавно состоялось очередное заседание. Как один из участников, поделюсь сегодня с Хабром свежими новостями и описанием изменений, которые...

Компиляция на этапе выполнения в C++: constexpr, consteval и constinit

Сегодня мы поговорим о том, как constexpr , consteval , и constinit позволяют реализовывать компиляцию на этапе выполнения. Компиляция на этапе выполнения позволяет ускорить выполнение кода за счет выполнения расчетов на этапе компиляции, а не в рантайме. constexpr делает возможным вычисление значений переменных во время компиляции. Функции и переменные, объявленные с этим ключевым словом, могут быть вычислены на этапе компиляции consteval усиливает концепцию constexpr , требуя обязательного вычисления выражений во время компиляции. constinit используется для инициализации статических и глобальных переменных. А теперь подробней.

habr.com/ru/companies/otus/art

#C++ #компиляция #constexpr #consteval #constinit

ХабрКомпиляция на этапе выполнения в C++: constexpr, consteval и constinitПривет, Хабр! Сегодня мы поговорим о том, как constexpr , consteval , и constinit позволяют реализовывать компиляцию на этапе выполнения. Компиляция на этапе выполнения позволяет ускорить выполнение...
Replied in thread

@talios @myfear Java already automatically does some of the #optimizations that #constexpr would enable (the OP mentions "Compile-time constant folding").

#ProjectLeyden seems to provide a framework for defining #condensers more easily. Perhaps a library can provide an `@ConstExpr` annotation alongside a #compiler plugin to do exactly what you would expect coming from a C++ background -- such as warn you when your expression isn't actually a compile time constant.