In C I am able to take two or more enumerated flags and inclusive OR them: (flag1 | flag2)
In C++ I cannot do the same thing. I have some flags that I've scoped to my class but to OR them I have to cast. It looks like this:
namespace name
{
class test
{
public:
enum flag
{
firstflag = 1, secondflag = 2, thirdflag = 4
};
void foo(flag flags)
{
return;
}
};
}
int main(int argc, char *argv[])
{
name::test obj;
obj.foo((name::test::flag)(name::test::firstflag | name::test::secondflag));
return 0;
}
That's kind of a mouthful, more in the real code than this example. I am wondering if there is a better way. I could change the argument passed to int void foo(int flags)
but then in the Visual Studio 2010 debugger I wouldn't see the flags ORed, just a number.
Without the cast I get an error:
obj.foo(name::test::firstflag | name::test::secondflag);
error C2664: 'name::test::foo' : cannot convert parameter 1 from 'int' to 'name::test::flag'
I searched on stackoverflow and found a question with the answer to overload the |
operator:
c++ - "enum - invalid conversion from int" in class - Stack Overflow
Yet when I use std::ios
flags I don't have to do any casting, why is that? For example fstream has a prototype like for example fstream(char *filename, std::ios_base)
and I can do this in my code:
fstream("filename", ios::in | ios::out);
What do you guys suggest? I do not have a lot of C++11 capabilities so if you could keep that in mind when answering. Thanks