How to rewrite this code without using boost?

后端 未结 2 895
抹茶落季
抹茶落季 2021-02-04 16:26

My task is to modify Sergiu Dotenco\'s Well Equidistributed Long-period Linear (WELL) algorithm code to not use boost (not saying boost is bad, but due to some company\'s policy

2条回答
  •  没有蜡笔的小新
    2021-02-04 16:44

    Using C++17, this code becomes way simpler and error messages are friendlier on the eye.

    This is a sample implementation of Power2Modulo:

    #include 
    
    template
    struct Power2Modulo
    {
      static_assert(std::is_unsigned_v);
      static_assert((r & (r - 1)) == 0,
         "The second parameter of this struct is required to be a power of 2");
    
      template
      [[nodiscard]] static constexpr T calc(T value)
      {
        return value & (r - 1);
      }
    };
    

    You can use it like this:

    int main()
    { 
      /* This code fails to compile with friendly error message
      Power2Modulo x;
      */
    
      // Using the static function
      using Mod16 = Power2Modulo;
      static_assert(Mod16::calc(15) == 15);
      static_assert(Mod16::calc(16) == 0);
      static_assert(Mod16::calc(17) == 1);
    
      // Using it like a member function
      Power2Modulo mod4;
      static_assert(mod4.calc(15) == 3);
      static_assert(mod4.calc(16) == 0);
      static_assert(mod4.calc(17) == 1);
    }
    

    Tested with clang-6 and gcc-8 and VisualC++ (via http://webcompiler.cloudapp.net/).

提交回复
热议问题