N
nick
I'm sort of rusty at C++, so this may be silly, but here's my
situation:
I have an enum like this:
enum ParserMode
{
PM_NONE = 0,
PM_READY = 1, // ready for next col or row, or EOF
PM_EMPTY = 2, // empty cell
PM_CELL = 4, // cell
PM_QCELL = 8, // quoted cell
PM_HEAD = 16, // header cell
};
And elsewhere I want to write something like:
void DoStuff(ParserMode m)
{
if (m & PM_HEAD)
...
else if (m & PM_QCELL)
...
}
...
DoStuff(PM_CELL | PM_EMPTY | PM_HEAD);
But this will not work, because the compiler complains about not being
able to cast between int and ParserMode. So some operator overloading
clears that up:
inline ParserMode operator|(ParserMode p1, ParserMode p2)
{
return (ParserMode)((int)p1 | (int)p2);
};
inline ParserMode operator&(ParserMode p1, ParserMode p2)
{
return (ParserMode)((int)p1 & (int)p2);
};
inline ParserMode operator~(ParserMode p1)
{
return (ParserMode)(~(int)p1);
};
inline ParserMode& operator&=(ParserMode& p1, ParserMode p2) {
p1 = p1 & p2;
return p1;
}
...
....And everything works fine. But, now I need to add another enum, and
I don't want to copy all of these overloaded operators for this other
enum. Is there some way I can share one set of operator overloads
between many enums using templates, macros, or some other trick, or am
I just going about this wrong altogether?
Thanks in advance for any help.
-- Nick
situation:
I have an enum like this:
enum ParserMode
{
PM_NONE = 0,
PM_READY = 1, // ready for next col or row, or EOF
PM_EMPTY = 2, // empty cell
PM_CELL = 4, // cell
PM_QCELL = 8, // quoted cell
PM_HEAD = 16, // header cell
};
And elsewhere I want to write something like:
void DoStuff(ParserMode m)
{
if (m & PM_HEAD)
...
else if (m & PM_QCELL)
...
}
...
DoStuff(PM_CELL | PM_EMPTY | PM_HEAD);
But this will not work, because the compiler complains about not being
able to cast between int and ParserMode. So some operator overloading
clears that up:
inline ParserMode operator|(ParserMode p1, ParserMode p2)
{
return (ParserMode)((int)p1 | (int)p2);
};
inline ParserMode operator&(ParserMode p1, ParserMode p2)
{
return (ParserMode)((int)p1 & (int)p2);
};
inline ParserMode operator~(ParserMode p1)
{
return (ParserMode)(~(int)p1);
};
inline ParserMode& operator&=(ParserMode& p1, ParserMode p2) {
p1 = p1 & p2;
return p1;
}
...
....And everything works fine. But, now I need to add another enum, and
I don't want to copy all of these overloaded operators for this other
enum. Is there some way I can share one set of operator overloads
between many enums using templates, macros, or some other trick, or am
I just going about this wrong altogether?
Thanks in advance for any help.
-- Nick