【发布时间】:2015-09-14 07:42:14
【问题描述】:
我在一个代表位标志的类中有一个枚举。
class Foo
{
enum Bar
{
BAR0 = 0x1,
BAR1 = 0x2,
BAR2 = 0x4,
};
}
我还为类 Foo 之外的枚举 Bar 定义了一个 operator|。
constexpr Foo::Bar operator| (Foo::Bar lhs, Foo::Bar rhs)
{
return static_cast<Foo::Bar>(static_cast<int>(lhs) | static_cast<int>(rhs));
}
我还希望有一个constexpr 变量BAR_ALL,它是Foo 类中Bar 的所有现有标志的组合。我尝试了以下但它没有编译错误error: #28: expression must have a constant value。
完整代码:
class Foo
{
enum Bar
{
BAR0 = 0x1,
BAR1 = 0x2,
BAR2 = 0x4,
};
friend constexpr Bar operator| (Bar lhs, Bar rhs);
static constexpr Bar BAR_ALL = BAR0 | BAR1 | BAR2;
};
constexpr Foo::Bar operator| (Foo::Bar lhs, Foo::Bar rhs)
{
return static_cast<Foo::Bar>(static_cast<int>(lhs) | static_cast<int>(rhs));
}
我想编译器不知道BAR0 | BAR1 | BAR2 是constexpr 是有道理的,因为该运算符是在代码后面定义的。我的问题是如何获得变量Foo::BAR_ALL 即constexpr 的预期效果。
提前感谢您的建议/帮助!
【问题讨论】:
-
你可能打算写
BAR1而不是BAR 1。 -
您是否尝试过使用 static constexpr int BAR0 = 0x1;等等?
-
@BoPersson 是的,谢谢。
-
@choosyg 我希望变量是枚举,所以它们有自己的类型。将来我可能会把它变成一个枚举类。我正在将我的项目从 C++03 移植到 C++11。
-
我不认为问题在于编译器不知道
operator|不是const_expr,你声明它是......我看到的更大问题是你投了@ 987654340@ 到Foo::Bar当您可以退出声明的值时。例如。你可以有3,但没有对应的Bar。这甚至允许吗?