c++c++11type-inferencereturn-type-deduction

What does auto mean in a return type, and when are explicit return types necessary?


  1. From Wikipedia

    What is the use of the keyword auto in this case (below) if not automatic type deduction?

    struct SomeStruct {
        auto func_name(int x, int y) -> int;
    };
    
    auto SomeStruct::func_name(int x, int y) -> int {return x + y; }
    
  2. What are some of the situations one needs to explicitly have types?


Solution

  • This is the trailing return type. auto is simply a placeholder that indicates that the return type comes later.

    The reason for this is so that the parameter names can be used in computing the return type:

    template<typename L, typename R>
    auto add(L l, R r) -> decltype(l+r) { return l+r; }
    

    The alternative is:

    template<typename L, typename R>
    decltype(std::declval<L>()+std::declval<R>())
    add(L l, R r)
    { return l+r; }
    

    It's likely that a future addition to the language will be to allow leaving out the trailing return type and instead using automatic type deduction as is permitted with lambdas.

    template<typename L, typename R>
    auto add(L l, R r) { return l+r; }