Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need auto after function concept arguments in C++20?

I have the following compile error which cause I am failing to understand.

template<typename T>
concept floating_point = std::is_floating_point_v<T>;

auto add(const floating_point f1, const floating_point f2)
{
    return f1+f2;
}

In the above vertion the compiler is complaining:

ssource>:6:16: error: expected 'auto' or 'decltype(auto)' after 'floating_point'
    6 | auto add(const floating_point  f1, const floating_point f2)

Wheras when I add the auto specifiers, all good.

auto add(const floating_point auto f1, const floating_point auto f2)
{
    return f1+f2;
}

This one works fine.

So the question really is why do we need auto here? (The signature seems odd to me)

The second question is what is the difference in return types:

floating_point auto add(..) vs auto add(..) for the same function? (Both compile)

like image 817
Eduard Rostomyan Avatar asked Jan 25 '23 07:01

Eduard Rostomyan


1 Answers

So the question really is why do we need auto here?

Because floating_point is not a type, and add is not a plain function. However, something like void add(floating_point, floating_point); totally looks like a regular function declaration, and nothing tells us here that this is actually a template written with terse syntax.

The committee felt uncomfortable having such ambiguity be a possibility in code. So the terse syntax was amended to require an actual type placeholder (auto) that the concept can bind to, and not look like a plain declaration.

The second question is what is the difference in return types

Those aren't types, those are placeholders meant to be deduced for some type.

The only thing the concept adds is that a return statement in add must return a type that passes the concept check, or the deduction will fail.

like image 58
StoryTeller - Unslander Monica Avatar answered Feb 21 '23 17:02

StoryTeller - Unslander Monica