Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++20 std::invocable syntax

Tags:

c++

c++20

I want to write this

    template <typename F, typename... Args> requires std::invocable<F&, Args...>
    void applyFunction(F&& f, Args&&... args) {

    }

without requires clause, so I want something like

template <std::invocable<F, Args...>>
    void applyFunction(F&& f, Args&&... args) {

    }

...but it fails to compile. I searched StackOverflow but couldn't find how to use the correct syntax. How can I use terse syntax correctly?

UPDATE: I found that this works:

    template <typename... Args, std::invocable<Args...> F>
    void applyFunction(F&& f, Args&&... args) {

    }

Still ugly. Any better way?

like image 793
frozenca Avatar asked Mar 04 '26 05:03

frozenca


1 Answers

Using a concept in place of typename in a template parameter list only works when you are replacing one of the concept's template parameters. Specifically, the first one.

If you have two (or more) template parameters that share a relationship, odds are good that you will need to have a requires clause. And you need to make your peace with that. Indeed, putting the parameter pack in front of the function as you have done in the template argument list has consequences. It pretty much impossible for a user to specify the callable type parameter directly when calling the function, and thus the user would be forced to rely on template argument deduction.

Don't try to force syntax to work just because it takes a couple fewer keystrokes to type. Write in the way that makes the most sense for what you're doing, that makes it the most clear as to what is going on.

like image 57
Nicol Bolas Avatar answered Mar 05 '26 20:03

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!