Is there an intent behind the auto keyword in return type syntax of return type?

In C ++ 11, two lines are equivalent. From what I see, the advantage of the second syntax is that the return type is in the class. Thus, you can use both nested class types and decltypenon-static member expressions . Moreover, function names line up well.

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

It uses a keyword autothat can also be used to automatically obtain the type of local variables. However, I do not see an analogy here. The function declaration syntax fails. The return type is clearly indicated behind the arrow.

Personally, I would say that the syntax would be more understandable without a keyword auto. Are there any intentions behind this? What?

+4
source share
2 answers

In the document "Decltype (version 5)", N1978 proposed a syntax of the type trailing-return-type (as they are now known). This was done to simplify the definition of function templates whose return type depends on the expression that includes its arguments in chapter 3:

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

(*(T*)0) - T , T . , :

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

, [Str02]. , , ; .

auto, , . ->, cv- - :

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

[Str02] - "Bjarne Stroustrup". "typeof". ++ ++ std-ext-5364, 2002 . ", , .

+4

@dyp.

, :

    template<class F, class... ArgTypes>
    auto expected_from_code(F&& f, ArgTypes&& ...args)
    -> expected_t<
    typename std::enable_if<
    !std::is_void<decltype(f(std::forward<ArgTypes>(args)...))>::value,
    decltype(f(std::forward<ArgTypes>(args)...))>::type>
    {
        using expected = expected_t<decltype(f(std::forward<ArgTypes>(args)...))>;
        try {
            return expected { f(std::forward<ArgTypes>(args)...) };
        }
        catch(...) {
            return expected { typename expected::exception_sentinel{} };
        }
    }
0

All Articles