2019-04-16

Dynamic dispatching reloaded

In previous posts I was exploring a feature I am interested in, and which I have called in many different ways — here I will call it dynamic dispatching.

The previous articles:

Conclusion of those posts: out of the box only Perl6 has it.

The story went on like this: I stirred the net for a solution in C++. And I obtained it.

I asked on Reddit and the user alfps gave me a solution.

Unfortunately it needs a C++17 compilers. Indeed, I was able to change it so that now a C++14 compliant compiler suffices. Also, I've removed the usage of the syntax auto f() -> Type since the more common Type f() is good for me.

I haven't analyzed it yet to see how it really works and to check if it can fit my “needs”, but anyway running it gives the expected results:

sum(S,S)
sum(S,I)
sum(I,S)
sum(I,I)
!oops - operator() - No function corresponds to the argument types

The code:

It can be changed a little bit more to be more familiar, for example I don't see the point of

template<class Type> using P_ = Type*;

In fact, it can be eliminated in favor of the classic Type* instead of P_<Type>.

Anyway, it's a matter of taste, I suppose

Notes on C++14 and C++17

In order to make it possible to compile it with a C++14 compliant compiler, I didn't do very much.

Apparently, in C++17, and not before this version of the standard, they thought it would be nice to have a list after using, rather than forcing the programmer to write a list of using.

So

using cppx::P_;
using cppx::hopefully;
using cppx::fail;
// ...

can be written as

using cppx::P_,
      cppx::hopefully,
      cppx::fail;

Also, in C++17 a is_polymorphic_v was added, which is simply this:

template<class T>
constexpr bool is_polymorphic_v = is_polymorphic<T>::value;

I am always amazed by the holes in this incredible, huge, language. I've always seen it as insufficient, confusing and ugly to be programmed in. Not ideal for OO paradigm. Almost unusable, unless you stick to a subset to use it like a sort of enhanced C with patches of object orientation on it.

C++11 made it better — I believe auto, decltype and lambdas were key additions. It was a hope; but when I find changes like those I've shown above, I start to wonder what went wrong in the standardization process. Because there must be a story, a good one, for those things — the more they look minor, the more the story must be good.

No comments:

Post a Comment