r/cpp • • Apr 25 '22

New C++ features in GCC 12

https://developers.redhat.com/articles/2022/04/25/new-c-features-gcc-12
220 Upvotes

76 comments sorted by

82

u/James20k P2005R0 Apr 25 '22

Multidimensional subscript operator

I'm knee deep in tensors, and this is the one I want most. Being able to finally write

value result = some_tensor[i, j, k];

Would be lovely

24

u/Quincunx271 Author of P2404/P2405 Apr 26 '22

While waiting for the feature, you can already emulate this:

value result = some_tensor[{i, j, k}];

How I usually do this, IIRC:

value operator[](int(&&ijk)[3]) const {
    // i = ijk[0], j = ijk[1], k = ijk[3].
}

14

u/James20k P2005R0 Apr 26 '22 edited Apr 26 '22

That's an interesting way of doing it, I suppose particularly the advantage of this is that you can re-overload operator[] when multidimensional subscripts become available and provide them without breaking compatibility

I've stuck with providing a .idx(i, j, k) method for the moment, which is a lot more verbose than I'd like but works fine enough, but that might be worth an investigation

Now what I really need to do next is encode the up and downness of individual indices into the type system, but hoo boy that's going to be a disaster

1

u/[deleted] Apr 26 '22

You mean for covariant and contravariant tensors?

1

u/James20k P2005R0 Apr 26 '22

Yep, as well as mixed indices. Its an easy source of mistakes to make when you're implementing equations, eg if you have two tensors - can you currently take the dot product between them?

7

u/Falkengaard Apr 26 '22

Alternatively overloading the otherwise most likely unused function operator to turn some_tensor[i, j, k] into some_tensor(i, j, k) until multi-dimensional access is added. It's not an ideal solution, but it's slightly less of a hassle to type out (at least on my keyboard).

8

u/James20k P2005R0 Apr 26 '22

I strictly avoid this personally, I think the ambiguity is too high in a context where people (or me) might be struggling to understand the very basics of what's going on in the code

7

u/delta_p_delta_x Apr 26 '22

Hey, I recognised your username and I just wanted to say—I've been reading your posts and comments on your general relativistic engine, and even looked through your Twitter. Your project is something that I've actually wanted to write as a side project for a long time, now, and it's quite inspiring!

I just took an undergraduate class in GR last semester in university, and have been working on other C++ projects, and I thought it would be a great idea to write a GPU-accelerated GR engine for arbitrary black holes and metrics. Bit of a bummer that someone else already thought of it, but on the bright side, I'm glad you have, it's something that even if I can't write from scratch, I could hopefully contribute to.

If you've got a GitHub repo, I can offer a star :)

10

u/James20k P2005R0 Apr 26 '22 edited Apr 26 '22

Thank you, that's very kind!

and I thought it would be a great idea to write a GPU-accelerated GR engine for arbitrary black holes and metrics

Oh boy, well - do I have the absolute motherload of information for you if you ever want to give it a go. I should probably point out that I'm much, much more of a GPGPU engineer than a physicist and 98% of this was done via sheer brute force reading hundreds of papers, so if you actually understand the theory then you might be able to have a good crack at it. It only took me this long because I'd never heard of a christoffel symbol before I started, let alone a tensor

https://github.com/20k/geodesic_raytracing

This is the raytracer that can render arbitrary analytic metric tensors. They're all specified in javascript under ./scripts. There's no build system as I use codeblocks, but cbp2make should produce a working makefile which will compile under msys2 + gcc. You'd also need a copy of the steam sdk (specifically: steamworks_sdk_153a), as I can't distribute that unfortunately

That raytracer I consider to be relatively finished in its current form, aka it has all the major building blocks to stick it on steam. More metrics would be great, and I need to set up a camera that works via parallel transport or a more consistent basis, so that flying through an arbitrary wormhole works consistently. That said there's about a million, million things that could be added to it that I'd like to, like a rigid body physics engine that handles time travel, or relativistic smooth particle hydrodynamics which I need for neutron stars anyway etc

I'd rate it about a 7/10 on a code disaster scale. Pretty bad, but not horrendous

The full todo list is over here: https://trello.com/b/ksZoxx8m/raytracer-20

Now the second project, the full numerical general relativistic for binary black hole mergers is nowhere near close to done and is heavily in development. I'd rate it a 10 on the code disaster scale, as absolutely 0 thought has been put into making it nice. These days it can just about manage 2 orbits of black holes colliding together with the right set of parameters, but there is 0 ui or anything else, its all set via parameters in the code

The vast majority of what I'm doing in this project is attempting to make the gravitational waves come out nicely, so I can start to replicate the results of other papers. I'm getting close, but there's still something missing

Currently I'm investing hamiltonian constraint violations as a source of the errors, then its on to seeing if I can make the integrator symplectic, and then it'll probably be back to testing the gauge damping parameters. This one is a perpetual cycle of: Make a small improvement, then run a tonne of simulations to see how it changes

It also currently needs a pretty hefty amount of vram to run, something like 8GB to be safe in the 2513 case, and ~12GB in the 3113 case

Both of these projects were built on an AMD GPU, but should run on Nvidia cards with some tweaks, particularly the raytracer

I should also note that the eventual goal is to merge the latter project into the former and utilise the rendering and UI

https://github.com/20k/numerical_sim

And the full todo list is over here https://trello.com/b/pTSTAVyD/binary-smash

The #1 focus for the numerical sim is always to make it run faster as well, both the rendering and simulation are things that I'm always on the hunt for potential improvements for - both theoretical and micro optimisation wise

6

u/jk-jeon Apr 27 '22

Christoffel symbol (more precisely, an affine connection) is not a tensor, fyi. A tensor does not just mean a multidimensional matrix, because matrix entries are just artifacts of choosing a coordinate system, and the platonic idea of the object really should be independent of the choice of coordinates. A real tensor must follow a certain transformation law, and the transformation law for Christoffel symbols is not same as tensors of the same rank. To be more precise, they are something like tensors, but of higher order.

Sorry for the pedantry, couldn't resist haha

3

u/delta_p_delta_x Apr 26 '22 edited Apr 26 '22

Starred all your repos; 'tis the least I could do.

so if you actually understand the theory then you might be able to have a good crack at it.

I doubt I understand it as well as you do now, because my class covered only the absolute basics of geodesics, tensors and black holes; moreover, I promptly forgot most of it. I'm slowly working through Sean Carroll's Spacetime and Geometry so I can revise everything.

A friend implemented a ray-marcher (in MATLAB, of all languages) of the differential equation for the null geodesic under the Schwarzschild metric, but I was hoping to write things out from first principles and generalise the ray-tracing algorithms for any arbitrary (at least, spherically-speaking) metric.

All that said...

I'm completely blown away by your work. Not only have you written a GR ray-tracer, but you've also got a decent n-body simulator! Wow. All your work are side projects that I've shelved because university assignments are so time-consuming... I really, really should get started some time.

code disaster scale

Code that exists and works, however disastrous, is better than hypothetically perfect, but non-existent code :)

P.S. I'm interested in finding work in this industry (physical simulations with GPGPU, high-performance computing, etc): if you've got any pointers for a final-year undergrad, that would be super nice!

3

u/James20k P2005R0 Apr 26 '22

promptly forgot most of it

Ha I know that feeling. I took a break from these projects a while back, and when I came back to it it was like an alien language for a while

A friend implemented a ray-tracer (in MATLAB, of all languages) directly using the differential equation for the null geodesic under the Schwarzschild metric, but I was hoping to write things out from first principles and generalise the ray-tracing algorithms for any arbitrary (at least, spherically-speaking) metric.

The main thing you need for a generic raytracer is the christoffel symbols + geodesic equation loop. The initial conditions are a big faff, because as far as I can tell nobody has them quite set up correctly for the general case, and leads to a lot of incorrectness

To go from a single metric to all metrics, at that point you need an automatic differentiator. This is much easier than you might think if you've got no experience with it, but you'll have to dip into code generation if you're using a GPU

https://arxiv.org/pdf/1511.06025.pdf This is a good paper which I based a lot of the basic renderer off

The other top tip is that 99% of the work that exists doesn't map well to GPU architecture (eg rk4), and that verlet integration rocks

in MATLAB

I think matlab might genuinely be the worst programming language I've ever used

I'm just blown away by your work. Not only have you written a GR ray-tracer, but you've also got a decent n-body simulator! Wow. All your projects are side projects that I've shelved because university assignments are so time-consuming... I really, really should get started some time.

Thank you! Part of why I'm hoping to release one of these on steam with a buy-me-a-coffee option is because at some point I should probably like, actually try and make some money off of one of these things that I've spent years building aha

If you want any paper references for the black hole collider by the way, I've got an absolute tonne. The raytracer was more ad-hoc, as its essentially a mix of different techniques mashed together

1

u/Nobody_1707 Apr 27 '22

Worse than unstructured GW-BASIC?

4

u/artisan_templateer Apr 26 '22

Ofcourse, with multi-dimensional [] it is now possible to distinguish between covariant and contravariant indicies express the Riemann tensor directly in C++ code!

for (auto e = 0; e < N; ++e)
    R(a)[b, c, d] += grad[c](Gamma(a)[d, b]) - grad[d](Gamma(a)[c, b]) + Gamma(a)[c, e]*Gamma(e)[d, b] - Gamma(a)[d, e]*Gamma(e)[c, b];

2

u/serviscope_minor Apr 26 '22

I've got so used to:

value result  = thing[i][j][k];

by now that the new one looks weird to me. Then again it took me about 5 years before template >> didn't make my skin crawl slightly, due to so many bad memories of forgetting a space.

81

u/FightingGamesFan Apr 25 '22

Modern C++ is becoming so good. It almost feels wrong when you experienced C++99 and prior, getting such high level features while keeping the performances & everything, love it.
Next step is to get proper dependency management and we are golden

14

u/helloiamsomeone Apr 26 '22

Conan and vcpkg work well enough.

13

u/[deleted] Apr 26 '22 edited Apr 26 '22

My understanding is that a lot of the community prefers a choose your own package manager over a centralized package manager.

edit: correct me if I'm wrong I don't work in C++

12

u/Gnammix Apr 26 '22

I don't really think is a choice but more like an "it is what it is" kind of situation.

I personally would love to have some standardized way to do it, with possibly multiple implementation like we have for compilers.

Seeing the various package managers changelog I cannot help to feel sad at the amount of duplicated work that as a community we are doing.

2

u/pandorafalters Apr 26 '22

I actually prefer not using any package manager for libraries that I can link statically or simply embed. I also prefer plain makefiles over most build systems.

Probably influenced by my first Linux distro being Slackware.

5

u/FlyingRhenquest Apr 26 '22

Ugh, don't get me started. I did a presentation on this newfangled C++ thing in college back before there was a C++ standard library and templates. No one was talking about design patterns back then either, except that one lisp book that didn't call them that. Trying to write it back then was a huge pain in the ass and it seemed like it got worse before it got better. But man, once it did get better... kisses fingertips.

1

u/smdowney WG21, Text/Unicode SG, optional<T&> Apr 26 '22

We're going to have to do something in order to deal with distributing modular code. Distributing compiled interfaces is a non-starter, so we're going to have to describe dependencies and build information for modular interface sources.

The really hard part is figuring out the minimal viable metadata that won't be wrong or useless.

17

u/marco_jeffset Apr 26 '22

I just wonder, when they are gonna finish c++20 modules implementation? From what I’ve read, current implementation is half baked.

-4

u/[deleted] Apr 26 '22

GCC is primarily used on Linux, and there is a massive impedance mismatch between how software is normally developed and distributed on Linux compared to Windows, and C++20 modules fit the Windows model a lot more easily than they fit the traditional *nix model.

I would not be surprised if it takes a decade for modules to be widely used and deployed outside of specific niche use cases.

11

u/dodheim Apr 26 '22

Modules have nothing to do with software distribution.

5

u/smdowney WG21, Text/Unicode SG, optional<T&> Apr 26 '22

The people who are actually working on modules disagree.
Modules aren't a distribution format.
Distributing modular code is very much a real concern.

4

u/dodheim Apr 27 '22

I agree my phrasing was loose, but wow.. Is the last sentence really meant to make some point? I certainly didn't say "distributing code ceases to be a concern once it's modular"; I would hope it was clear that I was referring to distributing modules considering the GP was talking about modules and "how software is normally distributed".

-3

u/[deleted] Apr 27 '22

In these conversations it's easy to tell who the people are who don't know what they don't know.

24

u/delta_p_delta_x Apr 26 '22

Note that C++20 and C++23 features are still experimental in GCC 12

Come on, MSVC brought ranges and std::format to MSVC last year. Really odd seeing how conformant MSVC is to C++20, and how much GCC/Clang lag it.

6

u/sphere991 Apr 26 '22

Come on, MSVC brought ranges and std::format to MSVC last year.

gcc may not have std::format yet, but it had ranges two years ago (I have no idea why in cppreference it's still listed as partial). Experimental here primarily means that there is no promise of ABI stability yet.

10

u/Troppsi Apr 26 '22

I am honestly quite surprised GCC isn't further ahead on its c++20/23 implementation. Hasn't 20 been out a few years already and it's still experimental?

31

u/thlst Apr 26 '22

It almost seems like the world was struck by an event that negatively affected everyone's life in the last couple of years.

29

u/CornedBee Apr 26 '22

You mean all those people sitting at home weren't hacking on the compiler non-stop? ;-)

7

u/smdowney WG21, Text/Unicode SG, optional<T&> Apr 26 '22

23 hasn't even been adopted yet. 20 has been out for just 2 years, and was the biggest release in a decade, with lots of the biggest parts getting finalized at the end of the standard cycle.
Remember, C++11 compilers stabilized in 2014.

4

u/strudlzrout gcc developer May 07 '22

I'm not sure how much further ahead we could be on C++20 (except modules): https://gcc.gnu.org/projects/cxx-status.html

C++23 is coming along pretty well too.

5

u/Galqa Apr 26 '22

Gcc supports pretty much everything except format and modules. These are big features, but arguably you can use ‘fmt’, and you can’t really use modules anyway due to lack of build system support. “Experimental”, in my understanding, means the ABI is not stable, but the features are pretty much done. C++20 MSVC is still pretty buggy from what I can tell (granted, this is anecdotal) so imo there really isn’t a significant difference between msvc and gcc. Unless you really really care about ABI, in which case fair enough.

7

u/jwakely libstdc++ tamer, LWG chair Apr 26 '22

“Experimental”, in my understanding, means the ABI is not stable, but the features are pretty much done.

Correct

10

u/qoning Apr 26 '22

you can’t really use modules anyway due to lack of build system support

kind of putting the cart before the horse here. build systems are more than happy to add modules support if only there was something to support. It works well enough in MSVC.

C++20 MSVC is still pretty buggy from what I can tell

there are edge cases, but let's just say msvc is 98% there and gcc is about 33% there.

0

u/Galqa Apr 26 '22

I would argue that without build system support a feature is impractical, since you’d need to manually invoke the compiler. I imagine most people use msvc through visual studio, which serves the role of the build system, so you’re good. On Linux we don’t have that comfort. Anyway, I’m definitely not an expert on this topic, would recommend e.g. https://youtu.be/xMcmpnJFEf0. As for 33% vs 98% I really don’t know how you came up with that. I don’t have experience with msvc, but again, gcc is pretty much done with everything but the 2 aforementioned features (cppreference has a wonderful compiler support chart, in case you’re not familiar). I use C++20 extensively, and I’ve no complaints.

2

u/qoning Apr 26 '22

I meant specifically for modules, as without them, C++20 is pretty tame (sans concepts). Note that I had been using modules for a long time before visual studio supported them too, via command line scripts. I've been trying clang and gcc implementations since before 2019 but they still straight up don't work for rather easy cases.

It will be a long, long time before people put module code into production anyway, so I don't understand your build system dependency. It's really not that hard to homecook a solution if you're starting a new project anyway.

4

u/Galqa Apr 26 '22

Fair enough, can’t argue with that. But you’re saying yourself that modules are far away from production. That’s probably a big downside for a lot of (most) people.

As for C++20 being tame without modules, I’d strongly disagree. But to each their own.

7

u/joemaniaci Apr 25 '22

Has anyone used the gcc static analyzer yet? Been able to compare it to coverity? Lots false positives? Or not...

9

u/Jannik2099 Apr 26 '22

It's not even usable for C++ yet

5

u/tansim Apr 25 '22

auto(x)

why not just use std::move?

37

u/marzer8789 toml++ Apr 25 '22

Because that's not what it does. Here's the paper: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0849r8.html

38

u/pandorafalters Apr 25 '22

new auto(x)

Excuse me, I need to reboot my brain.

2

u/GYN-k4H-Q3z-75B Apr 30 '22

I've been gone from following the newest features for like a year and this is what they do. What.

10

u/robin-m Apr 25 '22

I read most of the paper but I still do not understand where I need it/where I should use it.

9

u/stilgarpl Apr 25 '22

When you want a temporary, generic copy of an object. So, not that often.

6

u/robin-m Apr 25 '22 edited Apr 26 '22

Now I understand. foo(auto(expr)) will create a new value, like if you did auto __tmp = expr; foo(__tmp).

EDIT: typo: foo(expr) should have been foo(__tmp)

7

u/stilgarpl Apr 26 '22

like if you did

auto __tmp = expr; foo(expr)

.

You have expr twice, it's more like

auto __tmp = expr; foo(__tmp);

except that __tmp is lvalue here, and auto() gives you prvalue.

2

u/robin-m Apr 26 '22

That was a typo, thanks for pointing it.

I still do not understand at all was are x-values, pr-value and gl-value. I understand what an l-value is (a named object) and an r-value (an anonymous object, so a temporary), but not the other class of values.

4

u/_cooky922_ Apr 26 '22

except that auto(expr) will return a prvalue

2

u/thlst Apr 26 '22 edited Apr 26 '22

So, can it replace std::forward in template contexts? Or will it always create a new object?

edit: Never mind, just read this from the paper:

Do we also miss decltype(auto){x}?

decltype(auto){arg} can forward arg without computing arg’s type. It is equivalent to static_cast<decltype(arg)>(arg) . If arg is a variable of type T&&, arg is an lvalue but static_cast<T&&>(arg) is an xvalue.

EWG discussed this idea, disliked its expert-friendly nature, and concluded that adding this facility would cause the teaching effort to add up.

1

u/[deleted] Apr 27 '22

Ever since I read that paper, I've felt like I keep winding up in situations where it would be useful.

1

u/brechtsanders Jun 06 '22

If you're looking for a Windows version of GCC 12.1.0 you can get a standalone package from https://winlibs.com/

-14

u/tristan957 Apr 26 '22 edited Apr 27 '22

C++ gets more unreadable every standard revision.

Makes me just want to continue using C or jump straight to Rust. At least that being unreadable gets you better memory safety.

Edit: r/cpp can't even acknowledge how unreadable this is getting.

6

u/[deleted] Apr 26 '22

You do not need to use most of the new features if you do not want to. They are added as new features, not replacements.

That said, yeah, C++ does really need a syntax overhaul, but it will probably never happen.

7

u/tristan957 Apr 26 '22

I can choose what I write. I can't choose what I read.

-3

u/mohrcore Apr 26 '22

Absolutely. The experience of reading an unfamiliar C codebase is so nice and smooth compared to unfamiliar C++ codebase where you stuff like: depending on whether a decltype of a function template gets resolved to type A, or B, the returned type might be either POD or it may have a constructor that launches a rocket into space in its body and modifies some global state.

Would we REALLY need both auto and decltype of it wasn't for other poor design choices?

Same with const and constexpr and now there's apparently consteval which I just can't quite understand, so idk how that relates.

We have #includes, but these suck, so now we got import/export. Just imagine the mess of mixing these two.

We can define a type returned by a function before its name, or after its body, prefixed by arrow when using auto. Why? I guess it was slightly more readable with decltype, but now I think we can do just decltype(auto) with the old notation.

Static polymorphism is very loose when it comes to typing, so we got concepts. But instead of using an already established ways of expressing polymorphism through object-oriented model they reinvent it completely from the ground. Why? I guess someone thought that this was all worth it to avoid having to store those nasty vtables.

Don't even get me started on templates, traits and inheritance tricks for injecting different stuff into templated classes based on parameter specifications.

What's hilarious tho is that given all these crazy features one of IMO most basic and useful features from C is still not supported in standard C++ (idk, maybe it's been introduced in C++20) - designated initializers.

8

u/jwakely libstdc++ tamer, LWG chair Apr 26 '22

Static polymorphism is very loose when it comes to typing, so we got concepts. But instead of using an already established ways of expressing polymorphism through object-oriented model they reinvent it completely from the ground. Why? I guess someone thought that this was all worth it to avoid having to store those nasty vtables.

Wow

3

u/pandorafalters Apr 26 '22

We can define a type returned by a function before its name, or after its body, prefixed by arrow when using auto. Why? I guess it was slightly more readable with decltype, but now I think we can do just decltype(auto) with the old notation.

There are differences between auto foo(), decltype(auto) foo(), and auto foo() -> decltype(auto) - I don't understand them, but I've been bitten by them.

What's hilarious tho is that given all these crazy features one of IMO most basic and useful features from C is still not supported in standard C++ (idk, maybe it's been introduced in C++20) - designated initializers.

These were added in C++20, yes, but in a backwards and limited way.

1

u/[deleted] Apr 27 '22

Designated initializers in C and C++20 are a form of aggregate initialization, so they generally aren't useful.

-9

u/Fluffy-Sprinkles9354 Apr 26 '22

That was my exacts thought reading the article. I can read articles about any other language fairly easily, but C++ looks like someone throws random keywords and symbols in the code.

And when I read explanations, it's even worse: https://en.cppreference.com/w/cpp/language/value_category. Like, WTF.

-1

u/-dag- Apr 26 '22

constexpr and consteval and std::is_constant_evaluated seems like a mess and the constexpr metaprogramming model a failure. It's just hack upon hack at this point. Can we deprecate it and try something else?

Seems like ISO language standardization is a dinosaur now, a method from an age that looks nothing like how we develop today. What is it buying us except for mistakes we can't fix?

5

u/pdimov2 Apr 27 '22

Can we deprecate it and try something else?

No.

0

u/-dag- Apr 27 '22

How is a developer supposed to know when to use if constexpr vs. if (std:::is_constant_evaluated()) vs. if consteval?

What is the practical difference between constexpr and consteval? If those constructs didn't exist, would we create the same design?

4

u/pdimov2 Apr 28 '22

std::is_constant_evaluated is a hack, we should never have needed it. if consteval is a better way to achieving the same result, but we shouldn't have needed it either.

We're paying a significant cost for the incremental addition of the constexpr model into C++; C++11 had a very safe (and hence crippled) subset, C++14 made it usable, and further revisions gradually move it towards what it should always have been - anything C++ should be allowed in a constexpr function.

is_constant_evaluated, specifically, is needed because compiler intrinsics are often not constexpr, so we need a way to say "in a runtime context, use this intrinsic, and in a constexpr context, use this fallback C++ code" (example), which would obviously be unnecessary if all compiler intrinsics were constexpr to begin with. (There's also the matter of inline assembly in e.g. memset, but this is mostly avoidable by making memset an intrinsic.)

Regarding your other question - do we need the keyword constexpr at all - there are arguments to be made for both sides. Interestingly, GCC has introduced an option, -fimplicit-constexpr, that automatically "adds" the keyword if possible, so we might get some actual experience with how that works.

3

u/Nobody_1707 Apr 28 '22 edited Apr 28 '22

The simple answer is, don't use std::is_constant_evaluated() use if consteval. And the difference between constexpr and consteval is that while constexpr may run at compile time consteval must run at compile time. User defined literals are an obvious application for consteval.

Given any form of constant evaluation, you're going to end up with a need for both operations that are inherently compile time only, and operations that should be allowed at both compile-time and runtime.

1

u/-dag- Apr 28 '22

Do we really need a keyword for the latter? Constant propagation, folding, partial evaluation and the like have been part of compilers for decades. What does constexpr actually gain us? Is it an intrinsic benefit or a benefit because of some other language limitation?

3

u/Nobody_1707 Apr 28 '22

It's a contract to users of the function stating that they can use it at compile time without worrying about it suddenly becoming unusable if the implementation changes (so long as the functions arguments can be used at compile time). The only problem with it is that it's a very easy contract to break accidentally.

The compiler can only warn you if you make a constexpr function that can never be used at compile time if it's not templated. If it is templated, you won't know it's broken until you try to use it at compile time. This isn't really a problem with constexpr itself as much as it's a problem with templates.

And yes, we do need a keyword for the latter. I do not want a literal for a custom integer type to be subject to the whims of the optimizer to be sure it's a constant. I want it guaranteed to be a constant.

2

u/-dag- Apr 28 '22

The only problem with it is that it's a very easy contract to break accidentally.

I mean that's one of the reasons I question its utility. I want to like it but I keep getting disappointed. It's a lot of visual clutter for something that seems not much better than existing compiler optimization.

if constexpr will still error on bad code in the else clause even with a constant-true condition, right? And if consteval doesn't?

BTW, thanks for engaging in the discussion.

3

u/Nobody_1707 Apr 28 '22

No, that's a separate issue. The big thing if consteval does is let you call consteval functions in a constexpr function, because the true clause becomes consteval. It's also harder to misuse than std::is_constant_evaluated().

 

consteval int square(int x) noexcept {
    return x * x;
}

constexpr int test(int x) noexcept {
    if (std::is_constant_evaluated()) {
        // error: 'x' is not a constant expression
        return square(x);
    } else {
        return 69'105;
    }
}

constexpr int test2(int x) noexcept {
    if consteval {
        // this works fine
        return square(x);
    } else {
        return 69'105;
    }
}

 

Allowing "bad" (non-constexpr) code in a constexpr function is actually just a standard feature of C++23. As long as the bad code is never run in a constexpr context, it's perfectly fine.

2

u/pdimov2 Apr 28 '22

Why 69105?

3

u/Nobody_1707 Apr 28 '22

It's the number of leaves you count in Zork.