3 ms·
That's not how you do type erasure in C++. Have a look at std::any : https://en.cppreference.com/w/cpp/utility/any/ https://en.cppreference.com/w/cpp/utility/a
by einpoklum 6y ago
That's not how you do type erasure in C++.
Have a look at std::any :
https://en.cppreference.com/w/cpp/utility/any/ https://en.cppreference.com/w/cpp/utility/any/
you can place a value of any type T in it (well, obviously it needs to be constructible etc.), or a std::nullopt, which is like an "Empty" or "Nothing" indicator that is not in T.
Then you can pass the `any` around without knowing its type. Finally, when you want to restore the typed value, you use any::get<T>(). It will succeed if T is the correct type, and throw an exception otherwise.
This was introduced into C++ in the C++17 version of the standard. Before, it existed as a Boost library facility.
- aptxkid 6y agoHowever the Type Erasure described here doesn't need to know T even when you use it. E.g. it enables things like for (auto x : vec) { x.foo(); }
- jhgb 6y agoIs this the thing that's called "Voldemort types" in D?
- LaLaLand122 6y agoAnd if it were in the standard there wouldn't be at least five well known libraries implementing it (including from Adobe and from Facebook): https://github.com/boost-ext/te#similar-libraries https://github.com/boost-ext/te#similar-libraries As far as I know (I don't really follow the committee work) the latest attempt to introduce run-time duck-typing in the standard was https://github.com/andyprowl/virtual-concepts https://github.com/andyprowl/virtual-concepts, which seems dead.
- einpoklum 6y agoAt the link, the library description says: > run-time polymorphism (type erasure) I would argue that it's the first rather than the second.
- einpoklum 6y agoThat's because it's not type-erasure; it's essentially access through a base class pointer with some sugar on top so that it doesn't look like `x->foo()`.