C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Concept Overloading in C++

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Tue, 19 Dec 2023 12:05:12 -0500
On Tue, Dec 19, 2023 at 10:29 AM Giuseppe D'Angelo via Std-Proposals <
std-proposals_at_[hidden]> wrote:

>
> If you want something like this instead:
>
> > template <typename T>
> > concept is_summable = requires(T x) { x + x; };
> >
> > template <typename T, typename U>
> > concept is_summable = requires(T x, U y) { x + y; };
>
> This sounds more interesting, but then again, you can't redeclare any
> templated entity with a different set of template arguments.
>
> The Standard simply calls the second version of the concept `_with`.
>

+1, that's the normal approach used consistently throughout the STL:
`summable` and `summable_with`.

However, there's nothing stopping OP from writing the following if he
really wants to:
    // https://godbolt.org/z/8xqzTxcjG
    template<class T, class U = T> concept summable = requires (T t, U u) {
t + u; };
    template<summable T> void sum(T t) { return t + t; }
    template<class T> void sum(T t, summable<T> auto u) { return t + u; }
Or even:
    // https://godbolt.org/z/bfKnvPMch
    template<class... Ts> concept summable = requires (Ts... ts) { (ts +
...); };
although notice that that means something different (and less natural) for
a single argument — in that case `requires summable<T>` basically means
`requires true`.

Also note in passing that "Concept Overloading" is already a name for
something in C++:
https://quuxplusone.github.io/blog/2021/06/07/tag-dispatch-and-concept-overloading/
https://www.stroustrup.com/good_concepts.pdf

–Arthur

Received on 2023-12-19 17:05:26