c++templatestrailing-return-typereturn-type-deduction

Advantages of arrow syntax in function declaration


what are the advantages of using

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

over

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

isn't it compiled into the appropriate type during template instantiation?


Solution

  • what are the advantages of using [trailing return type syntax] ?

    A possible advantage: the trailing return type is SFINAE friendly.

    Your getsum() function, with trailing return type (-> decltype( l + r )), is enabled only when exist an plus operator between l and r.

    If you call it with a couple of arguments that doesn't support the sum (by example, a couple of std::vector's) you get a substitution failure that isn't an error (SFINAE).

    So another getsum() function can be called.

    The following is a full example that compile and where the "do something different" version is called from getsum(a, b)

    #include <vector>
    
    template <typename ... Ts>
    auto getsum (Ts...)
     { /* do something different */ }
    
    template <typename L, typename R> 
    auto getsum (L l, R r) -> decltype( l + r )
     { return l + r; }
    
    int main ()
     {
       std::vector<int> a, b;
    
       getsum(a, b);
     }
    

    But if you remove the trailing return type

    template <typename L, typename R> 
    auto getsum (L l, R r) // <<--- no more tailing return type!!!
     { return l + r; }
    

    the code doesn't compile anymore, because you don't have a substitution failure but an hard error.