【问题标题】:Templatize enum class operators模板化枚举类运算符
【发布时间】: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 &amp; Flags::four) 无法推断类型为 bool

我是模板新手,对模板推导机制有点迷茫。另外,我尝试创建创建转换运算符

operator bool(const Flags& flag)

但没有结果。

【问题讨论】:

  • 当你 | one two 和 three 你希望结果映射到什么标志?(目前它不映射到该枚举中的任何值!)
  • 返回类型的模板化运算符只允许以这种方式调用它:Flags::one.operator&lt;int&gt;&amp;(Flags::two)...你可能只想要Flags operator &amp; (Flags, Flags)。
  • @Nim Flags 在内部是 int 类型,我的想法是它能够在不明确定义的情况下保存多个值。
  • 我个人已经不再使用枚举作为多项选择标志的直接表示。您是否考虑过使用带有枚举的std::bitset 作为位集中的索引?通过这样做,您可以充分利用作用域和非作用域枚举,因为它不会衰减到底层类型并且不需要定义operator| 和operator&amp;。在我看来,它还可以在不牺牲任何性能的情况下更容易阅读代码。

标签: c++ c++11 templates operator-overloading


【解决方案1】:

首先创建一个帮助模板:

template<class E>
struct bool_or_enum{
  E e;
  explicit operator bool()const{return static_cast<bool>(e); }
  operator E() const {return e;}
};

接下来,创建一个特征函数并输入:

namespace magic_operators {
  template<class E>
  constexpr std::false_type algebraic_enum(E const volatile&) {return {};}

  template<class E>
  using use_algebra=decltype( algebraic_enum( std::declval<E const volatile&>() ) );
}

现在 magic_operators::use_algebra&lt;E&gt; 使用 ADL 搜索 algebraic_enum 重载,在 E 上返回 std::true_type。这允许在任何地方启用魔法。 MSVC 2015 缺乏足够的 C++11 支持来使用上述内容;替换为特征类。

肉:我们的运营商。将它们放入命名空间并使用using namespace 引入它们:

template<class E, std::enable_if_t<magic_operators::use_algebra<E>{}, int> = 0>
bool_or_enum<E> operator&(E const& lhs, E const& rhs){
  using U = std::underlying_type_t<E>; 
  return { E( static_cast<U>(lhs) | static_cast<U>(rhs) ) };
}

| 也类似。

对于~ 和^,您需要一个位掩码来保持定义的行为。有一个默认为 E::bit_mask 或类似的特征类 enum_mask&lt;E&gt; 来获取它。

template<class E, std::enable_if_t<magic_operators::use_algebra<E>{}, int> = 0>
bool_or_enum<E> operator^(E const& lhs, E const& rhs){
  using U = std::underlying_type_t<E>; 
  return { E( enum_mask<E>{} & (static_cast<U>(lhs) ^ static_cast<U>(rhs) ) ) };
}
template<class E, std::enable_if_t<magic_operators::use_algebra<E>{}, int> = 0>
bool_or_enum<E> operator~(E const& e){
  using U = std::underlying_type_t<E>; 
  return { E( enum_mask<E>{} & (~static_cast<U>(e)) ) };
}

由于对超范围枚举的标准要求,这很棘手。

|= 和 &amp;= 并不难,但确实需要编码。 = 和 |= 和 &amp;= 等同时支持赋值链和隐式 bool 需要更多的工作。我说不支持。

哦,标记所有constexpr 并将bool_or_enum&lt;E&gt; 重载添加到operators。

以上代码未经测试或编译,但设计有效。


最终结果是:

enum class Bob { a=2, b=7, bit_mask = 0x00ff };
constexpr std::true_type algebraic_enum( Bob const& ){ return {}; }
using namespace algebraic_ops;

int main(){
  Bob x=Bob::a;
  x = x | Bob::b;
  if( x &~ Bob::b ){
    std::cout << "cast to bool bitmasking!\n";
  }
}

或者类似的。

【讨论】:

    【解决方案2】:

    虽然@yakk-adam-nevraumont 很好用,但我宁愿不必为我的枚举类重新定义任何东西,而是让它们在我包含我的内联标题后自动获取运算符...

    所以,我做了这样的事情:

    #include <type_traits>
    
    namespace EnumUtils {
    
    template <typename T>
    constexpr bool is_class() {
        if constexpr (std::is_enum_v<T>) {
            return !std::is_convertible_v<T, std::underlying_type_t<T>>;
        }
        return false;
    }
    
    template <class EnumType>
    struct WrapperImpl {
        EnumType e;
    
        constexpr explicit WrapperImpl(EnumType const& en) : e(en) {}
        constexpr explicit WrapperImpl(std::underlying_type_t<EnumType> const& en)
            : e(static_cast<EnumType>(en)) {}
        constexpr explicit operator bool() const { return static_cast<bool>(e); }
        constexpr operator EnumType() const { return e; }
        constexpr operator std::underlying_type_t<EnumType>() const {
            return std::underlying_type_t<EnumType>(e);
        }
    };
    
    template <class EnumType>
    using Wrapper =
        std::conditional_t<is_class<EnumType>(), WrapperImpl<EnumType>, void>;
    }  // namespace EnumUtils
    
    template <class EnumType, class Wrapped = EnumUtils::Wrapper<EnumType>>
    constexpr std::enable_if_t<EnumUtils::is_class<EnumType>(), Wrapped> operator&(
        EnumType const& first, EnumType const& second) {
        return static_cast<Wrapped>(static_cast<Wrapped>(first) &
                                    static_cast<Wrapped>(second));
    }
    
    template <class EnumType, class Wrapped = EnumUtils::Wrapper<EnumType>>
    constexpr std::enable_if_t<EnumUtils::is_class<EnumType>(), Wrapped> operator|(
        EnumType const& first, EnumType const& second) {
        return static_cast<Wrapped>(static_cast<Wrapped>(first) |
                                    static_cast<Wrapped>(second));
    }
    
    template <class EnumType, class Wrapped = EnumUtils::Wrapper<EnumType>>
    constexpr std::enable_if_t<EnumUtils::is_class<EnumType>(), Wrapped> operator^(
        EnumType const& first, EnumType const& second) {
        return static_cast<Wrapped>(static_cast<Wrapped>(first) ^
                                    static_cast<Wrapped>(second));
    }
    
    template <class EnumType, class Wrapped = EnumUtils::Wrapper<EnumType>>
    constexpr std::enable_if_t<EnumUtils::is_class<EnumType>(), Wrapped&> operator|=(
        EnumType& first,  //  NOLINT(runtime/references)
        EnumType const& second) {
        first = (first | second);
        return reinterpret_cast<Wrapped&>(first);
    }
    
    template <class EnumType, class Wrapped = EnumUtils::Wrapper<EnumType>>
    constexpr std::enable_if_t<EnumUtils::is_class<EnumType>(), Wrapped&> operator&=(
        EnumType& first,  //  NOLINT(runtime/references)
        EnumType const& second) {
        first = (first & second);
        return reinterpret_cast<Wrapped&>(first);
    }
    
    template <class EnumType, class Wrapped = EnumUtils::Wrapper<EnumType>>
    constexpr std::enable_if_t<EnumUtils::is_class<EnumType>(), EnumType> operator~(
        EnumType const& first) {
        return static_cast<EnumType>(~static_cast<Wrapped>(first));
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      相关资源
      最近更新 更多