Hacker News new | past | comments | ask | show | jobs | submit login

Same question in chatgpt

https://chat.openai.com/share/36e9e015-8645-4c07-9131-d8d773...

Alright, let's dive into this. You're looking to modify your function to not use the `auto` keyword with parameter packs but instead use a template parameter. The thing is, when we talk about replacing `auto` with a template parameter in a situation like yours, it gets a bit tricky due to how parameter packs work with templates and concepts.

Your initial function definition is pretty sleek because it uses C++20 concepts (`std::same_as`) alongside `auto` to enforce that all arguments passed to `IsKeyDown` must be of the same type as `KeyCode`. This is cool because it gives you compile-time type checking right off the bat.

However, when you're looking to shift away from `auto` and use a template parameter list directly, you'd typically define a template that applies a concept to a type parameter. Unfortunately, the direct translation you're asking for, using `std::same_as<KeyCode>` directly in a template parameter list for a function, isn't how concepts are applied in template parameter lists. Here's how you can achieve a similar effect:

```cpp template<typename... Keys> requires (std::same_as<Keys, KeyCode> && ...) inline bool IsKeyDown(Keys... keys) { return (::IsKeyDown(KeyCodeToRaylibKey(keys)) || ...); } ```

In this version, `template<typename... Keys>` declares that `IsKeyDown` is a function template that accepts a variadic template parameter list named `Keys`. This means you can pass any number of arguments of any types to `IsKeyDown`, as long as they all meet the requirement defined by the `requires` clause that follows.

The `requires` clause here uses a fold-expression over the logical AND operator (`&&`) combined with the `std::same_as` concept to ensure that every type in `Keys` is the same as `KeyCode`. It's a way to say "all types in `Keys` must be `KeyCode`," which aligns with your original intent but doesn't use `auto`.

This approach maintains the compile-time check you wanted, ensuring all arguments to the function are of type `KeyCode`, and it doesn't use `auto` in the parameter list directly. It's a bit more verbose but achieves the goal within the constraints of the language and how templates and concepts interact.

Remember, this approach leverages C++20 features heavily, so make sure your compiler and build environment are up to date to support this syntax.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: