Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an intention behind the auto keyword in trailing return type function syntax?

In C++11, the two lines are equivalent. From what I see, the the advantage of the second syntax is that the return type is in class scope. Therefore, you can use both, nested types of the class directly and decltype expressions of non static members. Moreover, the function names line up nicely.

int foo(int bar);
auto foo(int bar) -> int;

The auto keyword is used here, which can also be used to automatically derive the type of local variables. However, I don't see the analogy here. In the function declaration syntax, nothing is derived. The return type is mentioned explicitly behind the arrow.

Personally, I would say that the syntax would be clearer without the auto keyword. Is there any intention behind this? Which?

like image 945
danijar Avatar asked Sep 29 '22 17:09

danijar


1 Answers

The paper "Decltype (revision 5)", N1978 proposed the syntax for trailing-return-type (as they're now known). This was done to simplify defining function templates whose return type depends on an expression involving its arguments in chapter 3:

template <class T, class U> decltype((*(T*)0)+(*(U*)0)) add(T t, U u);

The expression (*(T*)0) is a hackish way to write an expression that has the type T and does not require T to be default constructible. If the argument names were in scope, the above declaration could be written as:

template <class T, class U> decltype(t+u) add(T t, U u);

Several syntaxes that move the return type expression after the argument list are discussed in [Str02]. If the return type expression comes before the argument list, parsing becomes difficult and name lookup may be less intuitive; the argument names may have other uses in an outer scope at the site of the function declaration.

We suggest reusing the auto keyword to express that the return type is to follow after the argument list. The return type expression is preceded by -> symbol, and comes after the argument list and potential cv-qualifiers in member functions and the exception specification:

template <class T, class U> auto add(T t, U u) -> decltype(t + u);

The reference [Str02] is "Bjarne Stroustrup. Draft proposal for "typeof". C++ reflector message c++std-ext-5364, October 2002.", but I'm not sure if that's publicly available.

like image 85
dyp Avatar answered Oct 10 '22 03:10

dyp