Hacker News new | ask | show | jobs
by shortrounddev2 722 days ago
RTTI is a super vital feature for deserializing without having to generate code or write a ton of tedious boilerplate. I'd be very happy with RTTI in C++ and my life would be instantly easier if there were RTTI in typescript so I didn't have to use any of the hacky solutions out there for deserializing JSON on backends without RTTI.

I suppose C++'s template system might be able to generate JSON deserializers with static reflection as well

2 comments

You don't need RTTI to deserialize data in a clean way. What you need is return-type polymorphism. Haskell has this and it makes writing serializers and deserializers symmetric and totally painless.
Return type polymorphism and inheritance doesn't mix very well.

Swift got into this mess early in it's lifecycle and it's type checking is still more expensive than the rest of the compiler combined, and unpredictable on top of that.

Yeah if you ask me, inheritance is the one to go. Every time. Inheritance just makes things more complicated. It’s not a great tool of abstraction.
C++ has both return type polymorphism and inheritance. What it doesn't have is the kind of type inference that Haskell has. Its type inference is very limited.
You can't have two functions that differ in just the return type in C++
You can sort of do it so long as the return type is a template parameter.

    template<typename T>
    T my_construct() { T result; return result; }
That's not polymorphism as that template parameter won't be deduced in any context and you will always have to explicitly instantiate the template.
You certainly can and I know there are several JSON libraries that do it. The gist of it is to write a struct and overload the conversion operator for the set of return types you want to support, for example overload the conversion operator to int and std::string. As soon as the instance of that struct is used in a context that needs an std::string, then it calls the string overload.
You can, if you abuse C++ enough. I needed this very thing for a custom DSL.

    struct PolyReturn {
      const int value;
      operator int() const { return value; }
      operator bool() const { return value > 0; }
    };

https://cppinsights.io/s/f0b9976f
> I suppose C++'s template system might be able to generate JSON deserializers with static reflection as well

It definitely can, and it will be faster and more type-safe than doing it at runtime. But if you do want to do it at runtime, well, it's possible to implement runtime reflection as a library on top of compile-time reflection, so someone will probably do that.