【发布时间】:2016-10-24 12:27:30
【问题描述】:
我正在尝试使用 C++11 枚举类创建标志位域。我正在寻找一种方法来模板化运算符的返回类型,以便可以在下面的代码中使用它们:
#include <iostream>
enum class Flags {
one = 1,
two = 1 << 1,
three = 1 << 2,
four = 1 << 3
};
#define _CONVERT(_operator) \
static_cast<T>(static_cast<int>(lhs) _operator static_cast<int>(rhs))
template <typename T>
T operator & (const Flags& lhs, const Flags& rhs) {
return _CONVERT(&);
}
template <typename T>
T operator | (const Flags& lhs, const Flags& rhs) {
return _CONVERT(|);
}
#undef _convert
int main()
{
Flags flag = Flags::one | Flags::two | Flags::three;
if (flag & Flags::two)
std::cout << "Flag has two" << std::endl;
if (flag & Flags::four)
std::cout << "Flag has four" << std::endl;
std::cout << static_cast<int>(flag) << std::endl;
}
但是,有几个问题:
-
Flags flag = Flags::one | Flags::two | Flags::three;无法推断类型为Flags -
if (flag & Flags::four)无法推断类型为bool
我是模板新手,对模板推导机制有点迷茫。另外,我尝试创建创建转换运算符
operator bool(const Flags& flag)
但没有结果。
【问题讨论】:
-
当你
|onetwo和three你希望结果映射到什么标志?(目前它不映射到该枚举中的任何值!) -
返回类型的模板化运算符只允许以这种方式调用它:
Flags::one.operator<int>&(Flags::two)...你可能只想要Flags operator & (Flags, Flags)。 -
@Nim
Flags在内部是int类型,我的想法是它能够在不明确定义的情况下保存多个值。 -
我个人已经不再使用枚举作为多项选择标志的直接表示。您是否考虑过使用带有枚举的
std::bitset作为位集中的索引?通过这样做,您可以充分利用作用域和非作用域枚举,因为它不会衰减到底层类型并且不需要定义operator|和operator&。在我看来,它还可以在不牺牲任何性能的情况下更容易阅读代码。
标签: c++ c++11 templates operator-overloading