Hacker News new | past | comments | ask | show | jobs | submit login

Sometimes writing out the types make the code clearer (while auto is good for long type names like std::vector::iterator). And although this is an edge case, if you use template-expression libraries like Eigen, you are forbidden to use auto (otherwise the template deductions don’t work properly)



I'm curious of when this would actually happen. Some kind of recursive implicit specialization? AFAIK auto x=foo; is just sugar for decltype(foo) x=foo; rather than MLish inference.


The problem with the technique used by Eigen (and also Boost.Spirit among a few other famous libs), called expression templates, is that it leverages the fact that the references to temporaries in function calls will be maintained until the end of the expression. The last operation in the expression (assignment to a specific type) will do processing to preserve those temporaries, compute the result, etc...

e.g. it more or less looks like this in a trivial case :

    #include <cstdio>
    
    template<typename T1, typename T2>
    struct add {
      add(const T1& t1, const T2& t2): lhs{t1}, rhs{t2} { }
      const T1& lhs;
      const T2& rhs;
    
      constexpr auto get() const { return lhs.get() + rhs.get(); }
    };
    
    struct integer
    {
      const int& i;
      constexpr const int& get() const { return i; }
    };
    
    int f();
    int main()
    {
        auto x = add{add{integer{f()}, integer{f()}}, add{integer{f()}, integer{f()}}};
    }
Here, storing the value in `auto` is wrong because by the time the expression has ended, the references point to stuff that isn't in scope anymore

Hence the solution is to introduce a type that will actually do the computation or store the result during the expression ; but before C++11 you had to introduce a type here anyways, which is what was done and of course it worked.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: