Boost logo

Boost Users :

Subject: Re: [Boost-users] Map runtime value to type
From: dariomt (dariomt_at_[hidden])
Date: 2015-07-31 10:16:21


Leon Mlakar <leon <at> digiverse.si> writes:

> >
> > Say I have this code.
> > struct A {};
> > struct B {};
> > enum useType {useA, useB};
> >
> > template <typename F>
> > void g(useType w, F f)
> > {
> > switch (w)
> > {
> > case useA: A a; f(a);
> > case useB: B b; f(b);
> > }
> > }
> >
> > I need to generalize this to any number of enum values and any number
of
> > corresponding types.
> >
> > Something like this (pseudocode):
> >
> > typedef compile_time_map< mpl::pair<useA,A>, mpl::pair<useB,B>, ... >
> > mapping;
> >
> > template <typename F>
> > void g(useType w, F f)
> > {
> > switch_apply( w, mapping, f );
> > }
>
> Why not:
>
> std::map<useType, std::function<void(void)>> use_map = {
> { useA, [] { A a; f(a); } },
> { useB, [] { B b, f(b); } }
> };
>

Thanks for all the ideas.

I found a solution [1] based on boost::fusion::for_each() which looks
good enough for me (no variant, no heap allocations, no type-erasure).

I believe it should be functionally equivalent to an if-else chain, and
not as efficient as an actual switch, though.

Regards

[1] http://stackoverflow.com/questions/26846299/boost-fusion-run-time-
switch


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net