ysaie

31 / ⚧ / code, music, art, games

──────────────────────────────
🌸 many-shaped creature
✨ too many projects
🚀 cannot be stopped
🌙 stayed up too late
:eggbug: eggbug enjoyer
──────────────────────────────
header image: chapter 8 complete from celeste
avatar: made using this character builder


📩 email
contact@echowritescode.dev

it's if constexpr!


in C++ i can do this (contrived, i know, but bear with me):

template<typename T>
void foo() {
  if constexpr (std::integral<T>) {
    // this code is only compiled if T models std::integral
  } else {
    // this code is compiled in all other cases
  }
}

as far as i can tell, Rust has no equivalent for this (though i would be happy to be proven wrong). the only conditional compilation mechanism i'm aware of is #[cfg(...)], and i think this is not aware of the trait system or anything like that. in particular, i think you can't have the type/lifetime parameters of a generic function influence conditional compilation.

it is somewhat niche, but it can get you some very compact intuitive code, especially when one branch won't even compile for one case but will for the other. it's like getting two functions in one.


You must log in to comment.

in reply to @ysaie's post:

it is somewhat niche

Unless you're programming in D, where smashing all specialisations in a single declaration is an essential part of every day, and my terminal is filled with template instantiation points for a single error right now.

I know Rust had the introwospection project, but I think it's abandoned now?

that is an amazing name, but i can't find anything about it, so yeah probably abandoned?

haven't written basically any D besides downloading the toolchain and playing with it in high school (un?)fortunately. that sounds awful! like, it is useful, but it really depends on what you're writing. some stuff flows better as an if constexpr, some flows better as two separate function definitions.

introwospection.

that sounds awful!

But it's fun!
I get to write code like this treemap. I'm doing template constraints, type generation, creating fields and constants on the fly, all without a macro in sight!
Plus D's mixin is like eval but at compile-time, for more metaprogramming.
Like Lisp but better.

The fact that this is some people's nightmare is a plus in my eyes.