compile time loops

前端 未结 5 1827
时光说笑
时光说笑 2020-12-01 06:51

I would like to know if it is possible to have sort of compile time loops.
For example, I have the following templated class:

template

        
5条回答
  •  伪装坚强ぢ
    2020-12-01 07:04

    Here is, I think, a better version of the solution given above.
    You can see that we use the compile-time recursive on the function params.
    This enables putting all the logic inside your class, and the base case of Init(int_<0>) is very clear - just do nothing :)
    Just so you won't fear performance penalty, know that the optimizer will throw away these unused parameters.
    As a matter of fact, all these function calls will be inlined anyway. that's the whole point here.

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    template 
    class CountSketch {
     public:
      CountSketch() {
        memset(&_hashFunctions, sizeof(_hashFunctions), 0); // for safety
        Init(int_());
      }
    
      size_t HashAll(C& c)
      {
          size_t v = 0;
          for(const auto& h : _hashFunctions) 
          {
            v += (this->*h)(c); // call through member pointer
          }
          return v;
      }
    
     private:
        template
        size_t hash(C &c)
        {
            return (reinterpret_cast(&c)+offset)%B;
        }
    
      size_t (CountSketch::*_hashFunctions[N])(C &c);
    
     private: // implementation detail
    
      // Notice: better approach.
      // use parameters for compile-time recursive call.
      // you can just override for the base case, as seen for N-1 below
      template 
      struct int_ {};
    
      template 
      void Init(int_) {
        Init(int_());
        _hashFunctions[M - 1] = &CountSketch::template hash;
        printf("Initializing %dth element\n", M - 1);
      }
    
      void Init(int_<0>) {}
    };
    
    int main() {
      int c;
      CountSketch cs;
    
      int i;
      cin >> i;
    
      printf("HashAll: %d", cs.HashAll(c));
      return 0;
    }
    

    Compiler Explorer

提交回复
热议问题