How do I make this simple addition code less verbose?

I really don't get why it has to take so much to make such a little function. Here's what I have.

template <typename A, typename B> auto add(A a, B b) -> decltype(a + b) {
return a + b;
}


Is there a way to shrink this code while maintaining its ability to take different arguments? For a comparison, here is it in Python; there is a big difference between the two.

def add(a, b):
return a + b

• I think 3 lines is relatively short for a piece of code that supports all types that can be used with operator +. Without the declytype it would be infinitely long as you need to declare one for each combination. Sep 10, 2012 at 22:38
• There is a lot of difference between the two. In C++ you will see an error at compile time. In python you will not see the problem until it tries to execute the line. You pay for the convenience (and speed of C++). Sep 10, 2012 at 23:26
• @Loki While all of that is true, none of that justifies the verbosity. It could be made much terser (and maybe the next version will actually support this). Sep 11, 2012 at 6:53

You may want to take a look at Pythy.

What you want seems a lot like:

PYTHY(add, x, y) (
return x + y;
)


Make sure to read this part of the article, as pointed out by Konrad:

It appears that we are derefencing a null pointer. Remember in C++ when dereferencing a null pointer, undefined behavior occurs when there is an rvalue-to-lvalue conversion. However, since a non-capturing lambda closure is almost always implemented as an object with no members, undefined behavior never occurs, since it won't access any of its members. Its highly unlikely that a non-capturing lambda closure could be implemented another way since it must be convertible to a function pointer. But perhaps not?

• Indeed – but why not add a short example inline here? (And maybe mention the caveat, buried deep below in the blog post, that this is UB.) Sep 11, 2012 at 6:50
• Thanks for reminding me of that bit; I had read it thought "sounds reasonable", and entirely forgotten. :) Sep 11, 2012 at 16:19