What you can learn from being too cute

Why you should write code that you should never write

(Part 2 of N)

Daisy Hollman, Google

Pure Virtual C++ 2022
Twitter: @The_Whole_Daisy
Email: cpp@dsh.fyi

But why?

Goals for this talk

  • Have some fun geeking out about how weird C++ is sometimes
    • Sometimes you have to laugh to keep from crying
  • Learn something new about how C++ works
    • ...by using it in a way that's so bizarre that you can't forget it when it comes up in real code
    • (and learn the "right" way to do the same thing)
  • Learn about how to learn about the ways that dark corners of the language interact

Disclaimers

  • Don't use these tricks (directly) in "real" code
    • But do use them to learn things that will help you understand existing code
  • This is not a software engineering talk
    • Well-written code should be unsurprising
    • This talk is intentionally about code snippets that are surprising
  • I have a problem with my talks getting "too into the weeds"
    • 🤷🏼‍♀️ Sorry, this talk is all weeds 🌱
  • This talk is actually several mini-talks


Anyway...

Here we go!

🤷🏼‍♀️ 🌱 🌼

Trick 1: Assertions in constexpr contexts

Assertions in constexpr contexts

Cute C++ trick of the day: you can't use static_assert in a constexpr function for an expression that's dependent on function parameters ("constexpr" means "maybe this might be evaluated in a constant expression"). But you can just use assert as usual

What does constexpr mean?

What does constexpr mean?

It depends on which constexpr you mean!

  • constexpr variables
  • constexpr functions
  • constexpr if statements (a.k.a., if constexpr)
  • ...and more (we'll come back to this)

Different constexpr uses require different things to be constant expressions

  • constexpr variables require constant initializers
  • constexpr if statements require constant conditional expressions
  • constexpr functions require ???
    (Hint: it's not as simple as just "the function body")

What does constexpr mean (for a function)?

Look at how we can use it...

  • to initialize a constexpr variable...
  • in a static_assert...
  • as a non-type template argument...
  • ...as long as its arguments are also constant expressions!
  • But...constexpr functions can be used with runtime parameters!

What does "maybe" constexpr mean? (And why?)

What did I mean by "constexpr means maybe this might be evaluated in a constant expression"
  • A constexpr function that never can be used in a constant expression is ill-formed:
  • But it's the worst kind of ill-formed: 😱 no diagnostic required 😱
  • Templates are the same way with respect to template parameters
  • Why is this IFNDR?
    • We don't want to force compilers to solve "hard problems"

IFNDR, in a nutshell