impl_dyn_trait_wrapper

Macro impl_dyn_trait_wrapper 

Source
macro_rules! impl_dyn_trait_wrapper {
    ($dyn:ident, $trait_name:ident) => { ... };
    ($dyn:ident, $trait_name:ident, $(+ $marker_traits:ident)*) => { ... };
}
Expand description

Implements DynTrait $dyn wrapper for specified trait $trait_name.

DynTrait exposes reference to dyn $trait_name using as_object method. It also exposes necessary conversions to Any trait.

For example, you can define DynComponent trait that will inherit from both Component and Any:

use typedmap::impl_dyn_trait_wrapper;
trait Component {}
impl_dyn_trait_wrapper!(DynComponent, Component);

which expands to

trait DynComponent: ::std::any::Any {
    fn as_object(&self) -> &(dyn Component);

    fn as_any(&self) -> &dyn ::std::any::Any;
    fn as_mut_any(&mut self) -> &mut dyn ::std::any::Any;
    fn as_any_box(self: Box<Self>) -> Box<dyn ::std::any::Any>;
}
impl<T: Component + ::std::any::Any> DynComponent for T {
    fn as_object(&self) -> &(dyn Component) {
        self
    }

    fn as_any(&self) -> &dyn ::std::any::Any {
        self
    }

    fn as_mut_any(&mut self) -> &mut dyn ::std::any::Any {
        self
    }

    fn as_any_box(self: Box<Self>) -> Box<dyn ::std::any::Any> {
        self
    }
}

Optionally you can specify additionally marker traits, e.g. Send+Sync, for example:

use typedmap::impl_dyn_trait_wrapper;
trait Component {}
impl_dyn_trait_wrapper!(DynComponent, Component, +Send+Sync);

which expands to

trait DynComponent: ::std::any::Any + Send + Sync {
    fn as_object(&self) -> &(dyn Component + Send + Sync);

    fn as_any(&self) -> &dyn ::std::any::Any;
    fn as_mut_any(&mut self) -> &mut dyn ::std::any::Any;
    fn as_any_box(self: Box<Self>) -> Box<dyn ::std::any::Any>;
}
impl<T: Component + ::std::any::Any + Send + Sync> DynComponent for T {
    fn as_object(&self) -> &(dyn Component + Send + Sync) {
        self
    }

    fn as_any(&self) -> &dyn ::std::any::Any {
        self
    }

    fn as_mut_any(&mut self) -> &mut dyn ::std::any::Any {
        self
    }

    fn as_any_box(self: Box<Self>) -> Box<dyn ::std::any::Any> {
        self
    }
}

This DynTrait wrapper can be used as a Bounds::Container in Bounds implementation.