C++隐式转换为bool

Jos*_*ley 10 c++ conditional boolean implicit

为了使我的枚举更加类型安全,我一直在使用宏生成的重载运算符来禁止将枚举与除了相同类型的枚举之外的任何内容进行比较:

#include <boost/static_assert.hpp>

#define MAKE_ENUM_OPERATOR_TYPESAFE(enumtype, op) \
  template<typename T> \
  inline bool operator op(enumtype lhs, T rhs) \
  { \
    BOOST_STATIC_ASSERT(sizeof(T) == 0); \
    return false; \
  } \
  \
  template<> \
  inline bool operator op(enumtype lhs, enumtype rhs) \
  { \
    return static_cast<int>(lhs) op static_cast<int>(rhs); \
  }

#define MAKE_ENUM_TYPESAFE(enumtype) \
  MAKE_ENUM_OPERATOR_TYPESAFE(enumtype, ==) \
  MAKE_ENUM_OPERATOR_TYPESAFE(enumtype, !=) \
  MAKE_ENUM_OPERATOR_TYPESAFE(enumtype, >) \
  MAKE_ENUM_OPERATOR_TYPESAFE(enumtype, <) \
  MAKE_ENUM_OPERATOR_TYPESAFE(enumtype, >=) \
  MAKE_ENUM_OPERATOR_TYPESAFE(enumtype, <=)

// Sample usage:
enum ColorType { NO_COLOR, RED, BLUE, GREEN };
MAKE_ENUM_TYPESAFE(ColorType)
Run Code Online (Sandbox Code Playgroud)

这通常具有期望的效果; 表单color_variable == RED工作的比较,而表格的比较color_variable == 1由于Boost.StaticAssert而产生编译时错误.(这是一个不错的方法吗?)

但是,我的编译器(CodeGear C++ Builder)也试图使用这些重载的运算符来实现隐式bool转换.例如,if (color_variable) { ... }正在被翻译为if (operator!=(color_variable, 0)) { ... }并且正在触发BOOST_STATIC_ASSERT并且无法编译.

我很确定这是我的编译器不正确的行为(例如,Comeau和GCC没有这样做)但是想知道是否有任何语言律师可以确认.我自己试着查看C++ 0x草案标准,但我能找到的只是4.12节下面的声明:

零值,空指针值或空成员指针值转换为false; 任何其他值都转换为true.

没有关于如何检查"零值"的细节.

Ale*_*tov 4

为什么不使用如下所示的类?

template<class Enum>
class ClassEnum
{
public:
  explicit ClassEnum(Enum value) : value(value) {}
  inline bool operator ==(ClassEnum rhs) { return value == rhs.value; }
  inline bool operator !=(ClassEnum rhs) { return value != rhs.value; }
  inline bool operator <=(ClassEnum rhs) { return value <= rhs.value; }
  inline bool operator >=(ClassEnum rhs) { return value >= rhs.value; }
  inline bool operator  <(ClassEnum rhs) { return value < rhs.value; }
  inline bool operator  >(ClassEnum rhs) { return value > rhs.value; }

  // Other  operators...
private:
  Enum value;
}

enum ColorTypeEnum { NO_COLOR, RED, BLUE, GREEN };
typedef ClassEnum<ColorTypeEnum> ColorType;
Run Code Online (Sandbox Code Playgroud)

没有到 bool 的隐式转换ClassEnum<ColorTypeEnum>