|
Boost : |
Subject: Re: [boost] More flexible any_cast for boost::any
From: Antony Polukhin (antoshkka_at_[hidden])
Date: 2013-11-27 03:25:56
2013/11/26 DeadMG <wolfeinstein_at_[hidden]>
> Hello,
>
> I've been looking at ABIs and such (various unpleasant reasons). But I
> recently created the following code:
>
> #include <iostream>
>
> struct Base {
> virtual void check() = 0;
> template<typename T> T* IsDerivedFrom() {
> try {
> check();
> } catch(T* p) {
> return p;
> } catch(...) {
> return nullptr;
> }
> return nullptr;
> }
> };
>
> template<typename T> struct Derived : public Base {
> Derived(T obj) : t(obj) {}
> T t;
> void check() override final {
> throw &t;
> }
> };
>
> struct A { virtual ~A() {} virtual void print() = 0;};
> struct B : public A { int x; B(int y) : x(y) {} void print() override final
> { std::cout << x; } };
>
> int main() {
> Base* b = new Derived<B>(B(5));
> A* p = b->IsDerivedFrom<A>();
> p->print();
> }
>
> Whilst this is hardly the cleanest piece of code I've ever written, it also
> provides a base for implementing a more generic any_cast<ValueType>, which
> could succeed if ValueType is a base class of the stored type. Amazingly,
> the Standard requires the code to work but does not provide a cleaner means
> of implementation.
>
This is a very interesting approach. But it has two drawbacks, because of
exceptions usage:
* it is slow
* it won't work with exceptions disabled
This can be implemented as a separate `polymorphic_any_cast` cast that is
available only with exceptions on. In that way it won't affect performance
of the existing any_casts and will improve usability.
I'm not *the official* maintainer of the Boost.Any library, I'm just the
one who made all the latest changes with rvalues and C++11 support. But if
there'll be no objections and the official maintainer won't appear I can
add this functionality to Boost.Any.
-- Best regards, Antony Polukhin
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk