【问题标题】:How to overload the << operator for enums如何为枚举重载 << 运算符
【发布时间】:2019-07-20 04:15:49
【问题描述】:

我正在尝试为按位

我希望 static_assert 会告诉编译器 "file

“cout

  #include <fstream>
  #include <iostream>
  using namespace std;

  enum DAY{MON=1,TUES=2,WED=4,THUR=8,FRI=16};

  template<typename Enum>  
  constexpr Enum operator <<(Enum e,int n)  
  {
    static_assert(std::is_enum<Enum>::value, 
    "template parameter is not an enum type");

    using underlying = typename std::underlying_type<Enum>::type;
    return static_cast<Enum> ( static_cast<underlying>(e) << n );
  }

  int main()
  {
  // this does as I'd like
    DAY day = MON;
    day = static_cast<DAY>(day << 2); // this is the behavior I need
    cout << day << endl;

// but this is ambiguous
    ofstream file("test.dat");
    float x;
    file << x; // this line is ambigous
    return 0;
  }

【问题讨论】:

  • 你希望看到FRI &lt;&lt; 2的结果是什么?

标签: c++ templates overloading operator-keyword


【解决方案1】:

static_assert 应用太晚,无法将您的 operator&lt;&lt; 从重载解决方案中删除。您需要改用 SFINAE。这样的事情会做你想做的事:

template <typename Enum>
constexpr std::enable_if_t<std::is_enum_v<Enum>, Enum>
operator<<(Enum e, int n)
{
    using underlying = typename std::underlying_type_t<Enum>;
    return static_cast<Enum> ( static_cast<underlying>(e) << n );
}

Live Demo

【讨论】:

  • 谢谢,这正是我们所需要的!
猜你喜欢
  • 2017-12-28
  • 2010-11-24
  • 2011-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多