4
\$\begingroup\$

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
\$\endgroup\$
3
  • 3
    \$\begingroup\$ 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. \$\endgroup\$ Sep 10, 2012 at 22:38
  • 3
    \$\begingroup\$ 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++). \$\endgroup\$ Sep 10, 2012 at 23:26
  • \$\begingroup\$ @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). \$\endgroup\$ Sep 11, 2012 at 6:53

1 Answer 1

5
\$\begingroup\$

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?

\$\endgroup\$
2
  • \$\begingroup\$ 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.) \$\endgroup\$ Sep 11, 2012 at 6:50
  • \$\begingroup\$ Thanks for reminding me of that bit; I had read it thought "sounds reasonable", and entirely forgotten. :) \$\endgroup\$ Sep 11, 2012 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.