Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

c++ - How can I use an enum class in a boolean context?

I have some generic code that works with flags specified using C++11 enum class types. At one step, I'd like to know if any of the bits in the flag are set. Currently, I'm using the code:

if (flags != static_cast<E>(0)) // Works, but ugly.

I could also force users to specify a particular name for an all-zero field, which is more readable but imposes my naming conventions on anyone using it:

if (flags != E::none) // Works, if you manually define none = 0.

But neither of these reads as nicely as the traditional:

if (flags) // Doesn't work with class enums.

Is it possible to specify a custom function to evaluate a class enum in a boolean context?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Like @RMatin says. But you could overload operator!

bool operator!(E e) {
  return e == static_cast<E>(0);
}

So that you can use the !!e idiom

if(!!e) {
  ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...