Composite Assignment Operators for enums

D

David Rasmussen

Given an enum type E, how do I make, say, operator += work for that enum
type?

/David
 
A

Alf P. Steinbach

* David Rasmussen said:
Given an enum type E, how do I make, say, operator += work for that enum
type?

Best to avoid enum types.

C++ is not Ada, as we have discussed before a few times... ;-)

But if you absolutely must,


E& operator += (E& lhs, E rhs )
{
lhs = static_cast<E>( lhs + rhs );
return lhs;
}
 
D

David Rasmussen

Alf said:
Best to avoid enum types.

I disagree. To me, it's like saying "it's best to avoid ints".
C++ is not Ada, as we have discussed before a few times... ;-)

But hopefully, C++ will learn something from Ada as time goes on.
But if you absolutely must,


E& operator += (E& lhs, E rhs )
{
lhs = static_cast<E>( lhs + rhs );
return lhs;
}

Thanks!

/David
 
T

Thomas Matthews

David said:
Given an enum type E, how do I make, say, operator += work for that enum
type?

/David

By converting the enum into a class or providing global functions
to perform the operation.

http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.18
http://tinyurl.com/28ntu
http://cpptips.hyperformix.com/Enums.html
http://www.bearcave.com/software/java/misl/enum/type_safe_enum.html

You can get a lot of examples by typing "enumeration C++" into
your favorite search engine.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top