Boost logo

Boost Users :

Subject: Re: [Boost-users] Map runtime value to type
From: Michael Powell (mwpowellhtx_at_[hidden])
Date: 2015-07-31 10:33:43


On Fri, Jul 31, 2015 at 9:54 AM, Leon Mlakar <leon_at_[hidden]> wrote:
> On 31.07.2015 15:10, dariomt wrote:
>>
>> Michael <mwpowellhtx <at> gmail.com> writes:
>>>
>>>
>>> On July 31, 2015 6:01:04 AM EDT, dariomt <at> gmail.com wrote:
>>>>
>>>> Hi all,
>>>>
>>>> Say I have a compile-time map of <value,type> pairs, and I need to
>>>> access
>>>> the correct element given a value at runtime and do something with
>>
>> that
>>>>
>>>> type. That something would be the same for any of the mapped types
>>>> (e.g.
>>>> calling an overloaded function that would then do the right thing
>>>> depending
>>>> on the type).
>>>>
>>>> The value would typically be an enum.
>>>>
>>>> Is there anything in the Boost libraries to help with this?
>>>>
>>>> If I used C++11, would there be a simple solution to this?
>>>
>>> Not really a boost question, perhaps.
>>
>> I thought asking if Boost has tools to help with certain C++ problem was
>> allowed in this list. Please correct me if I'm wrong.
>>
>>> First, I'm not sure why anyone wouldn't leverage at least C++11+.
>>
>> Especially considering compiler
>>>
>>> advancements in recent history. Optimization technology being what it
>>
>> is and all.
>> I'd rather use a well tested Boost component than a C++11 solution I have
>> to implement, test and document.
>>
>>> That said, if it was me, I might have a look at a std::function (or
>>
>> boost::function) "type factory" that knew
>>>
>>> how to interface with an instance repository.
>>>
>>> Could be a functor instance, as well, for that matter.
>>>
>>>> Regards
>>>
>>> Cheers.
>>>
>>>> PS: I cannot use Boost.Variant
>>>
>>> Why not?
>>>
>> Sorry, it is clear I didn't explain my problem well enough.
>>
>> 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); } }
> };
>
> then:
>
> usemap.at(w)();
>
> Or something similar ...

Exactly along the lines what I described.

> Cheers,
>
> Leon
>
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users


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