r/cpp_questions • • 5d ago

OPEN Can you recommend a good source for learning constexpr/consteval patterns?

The specific thing I'm thinking of right now is a function that looks like:

auto func(auto... args)
{
    for each arg {
        if arg is type T {
            do a thing with T
        }
        else if arg is type U {
            do a thing with U
        }
        else {
            compile error
        }
    }
}

but I'm not just looking to solve just this specific issue, I'd like to learn a substantial amount of this skillset.

4 Upvotes

10 comments sorted by

7

u/fm01 5d ago

Maybe tell us where you feel like you're missing knowledge, because if clauses like that are not any different from runtime clauses except you put 'if constexpr' and a compile time condition. There's really not much difference in structure between runtime and compile time code, you just need to check that you only use classes and functions that can be compile time evaluated

1

u/SoerenNissen 5d ago

It's less that I know what I'm missing and more that I don't know what I'm missing.

I'm reading the c++23 and c++26 accepted papers but that's dry and, more importantly, they're not a teaching resource. They don't set out to give a good toolbox for future work. I'm afraid it could be like reading drink recipes without knowing that alcohol makes you drunk, like there might be huge chunks of missing knowledge.

1

u/fm01 5d ago

I agree that the c++ standard would probably not be a good place to learn things like this. However there really is not that much to learn here, if you are already familiar with c++, and there are no "compile-time-patterns", it's just normal code that can/must be evaluated at compile time. To write compile time code, make sure you understand heap vs stack allocation, what structures and functions from the stl (don't) support compile time evaluation and what disqualifies compile time evaluation (e.g. virtual destructors, runtime data or information about the runtime environment). For your example above, you should look into concepts, as these are usually what you use as compile time conditions (or _v/::value structs in pre 23) and the definition of if constexpr. It could also help to read up on variadic templates/ fold expressions and std::apply as templates are used often in compile time code due to them being inherently a compile time feature. If you're feeling spicy you can also look into how gating code with ifdef macros works.

Happy to help if you have further questions

3

u/n1ghtyunso 5d ago

typical patterns are partial class template specialization and certain fold expression tricks.
looking up that alone should already give you a nice set of tools.

Apart from that, its really vague on what exactly you are looking for generally.

1

u/SoerenNissen 5d ago

The whole thing. All of the compile time programming that's available with constexpr/consteval instead of the old way with template trickery.

Which is a large subject for sure, that's why I'm asking for a learning source, rather than asking for all the rules.

3

u/TotaIIyHuman 5d ago

if you need early return

you can do short circuiting with && instead of , for folding

#include <utility>
constexpr auto func(auto...args)
{
	int result{};
	(...,[&]
	{
		/* */if constexpr(std::same_as<int,   std::remove_cvref_t<decltype(args)>>) result += 1;
		else if constexpr(std::same_as<float, std::remove_cvref_t<decltype(args)>>) result *= 2;
		else static_assert(0);
	}());
	return result;
}
static_assert(func(0, 0.f) == 2);
static_assert(func(0.f, 0) == 1);

to learn a substantial amount of this skillset

probably code a lib that involves lots of meta programming

2

u/SoerenNissen 5d ago

I have - including the compile time loop - but it's mostly template stuff, nothing newer than c++20, and rather complex to understand every time I return to it.

I'm hoping to to simplify it by adopting new language features, but I need to understand the language features first - not just to use them, but also to ensure I use them well and don't miss out on a feature somewhere that could have simplified more things.

2

u/TotaIIyHuman 5d ago

nothing newer than c++20

heres a table of old vs new that i can think of

if there some rows are new to you, just experiment on godbolt for 20min, you will probably figure it out

also i did not include any c++26 stuff (because unfamiliarity), wouldn't be surprised if there are easier ways to do below things with c++26 features

oldnewcompletely replaced?
std::void_t std::enable_if_trequires conceptsyes
crtpdeducing thisno
recursive template instantiationsfold exprno
template specializationsif constexprno
[]<auto...I>(std::index_sequence<I...>{}(std::make_index_sequence<N>{}))template for static constexpr auto [...I]{std::make_index_sequence<N>{}}+fold expryes (i think?)

-1

u/New-Step3500 5d ago

I made a video on compile time evaluation https://youtu.be/9-8GPx2UdBo

1

u/SoerenNissen 5d ago

I'll take a look.