Boost logo

Boost :

Subject: Re: [boost] Enum Conversion
From: Ilya Bobyr (ilya.bobir_at_[hidden])
Date: 2012-09-03 19:12:07


On 9/3/2012 4:01 PM, Ilya Bobyr wrote:
> On 9/2/2012 1:46 PM, Vicente J. Botet Escriba wrote:
>> [...]
>> I managed defining a specific opaque type, let me say MyGreek, and
>> defining implicit conversions from these types.
>>
>> Your example could be written as
>>
>> std::cout << string(MyGreek(1)) << std::endl;
>> std::cout << string(MyGreek(6)) << std::endl;
>> std::cout << MyGreek(Alpha) << std::endl;
>> std::cout << MyGreek::Alpha << std::endl; // using nested literal
>> std::cout << string(MyGreek(Alpha)) << std::endl;
>> std::cout << string(MyGreek::Alpha) << std::endl; // using nested
>> literal
>> std::cout << MyGreek(17) << std::endl;
>>
>>
>> If think this interface corresponds more to how C++ conversions work
>> (IMO of course).
>>
>>
>>> (Or
>>> does boost even offer something like that already?)
>> I don't think so. The closest could be TBoost.Enums in the sandbox,
>> but this library generates the enum and don't do the mapping.
>
> I think that it can do both plain enums and enums that map to
> arbitrary types. Here is an example where string are associated with
> enum values:
>
> http://stackoverflow.com/a/439004
>
> The syntax is different but the function is the same.
>
> BOOST_ENUM_VALUES(Greek, int,
> (Alpha)(5),
> (Beta)(3),
> (Gamma)(7),
> (Delta)(1),
> (Epsilon)(6)
> );
>
> /*
> class Greek {
> ...
> typedef boost::optional<Greek> optional;
> ...
> */
>
> Greek::optional gammaVal = Greek::get_by_name("Gamma");
s/Level/Greek/g

And the other way around:

if (gammaVal)
     const char * gammaName = gammaVal->str();

You can also do

Greek::optional gammaVal = Greek::get_by_value(7);

P.S. Sorry for the two emails instead of one.

-- 
Ilya Bobyr

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk