I recently worked with a friend who wanted to make C ++ more Haskell-y, and we need a function that basically looks like this:
auto sum(auto a, auto b) { return a + b; }
Apparently, I cannot use auto as a parameter type, so I changed it to this:
template<class A, class B> auto sum(A a, B b) { return a + b; }
But that doesn't work either. What we finally understood, we need this:
template<class A, class B> auto sum(A a, B b) -> decltype(a + b) { return a + b; }
So my question is, what's the point? Isn't decltype just repeating the information, since the compiler can just look at the return statement?
I thought it might be necessary, so we can just include the header file:
template<class A, class B> auto sum(A a, B b) -> decltype(a + b);
... but we still cannot use such patterns.
The other thing I considered was that the compiler might be simpler, but it seems like it will actually be more complicated.
Case 1: with decltype
- Find out the type of
decltype - Find out return types
- See if they match
Case 2: Without decltype
- Find out return types
- See if they match
So, with these things in mind, what is the point of return type with decltype ?
c ++ c ++ 11
Brendan Long Sep 28 '11 at 9:26 a.m. 2011-09-28 21:26
source share