C++11: Compile Time Calculation of Array

前端 未结 7 2082
长发绾君心
长发绾君心 2020-11-28 05:25

Suppose I have some constexpr function f:

constexpr int f(int x) { ... }

And I have some const int N known at compile time:

Either<

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 05:54

    I slightly extended the answer from Flexo and Andrew Tomazos so that the user can specify the computational range and the function to be evaluated.

    #include 
    #include 
    #include 
    
    template 
    struct ComputeEngine
    {
      static const int lengthOfArray = max - min + sizeof... (expandedIndices) + 1;
      typedef std::array FactorArray;
    
      static constexpr FactorArray compute( )
      {
        return ComputeEngine::compute( );
      }
    };
    
    template 
    struct ComputeEngine
    {
      static const int lengthOfArray = sizeof... (expandedIndices) + 1;
      typedef std::array FactorArray;
    
      static constexpr FactorArray compute( )
      {
        return FactorArray { { ComputePolicy::compute( min ), ComputePolicy::compute( expandedIndices )... } };
      }
    };
    
    /// compute 1/j
    struct ComputePolicy1
    {
      typedef double ValueType;
    
      static constexpr ValueType compute( int i )
      {
        return i > 0 ? 1.0 / i : 0.0;
      }
    };
    
    /// compute j^2
    struct ComputePolicy2
    {
      typedef int ValueType;
    
      static constexpr ValueType compute( int i )
      {
        return i * i;
      }
    };
    
    constexpr auto factors1 = ComputeEngine::compute( );
    constexpr auto factors2 = ComputeEngine::compute( );
    
    int main( void )
    {
      using namespace std;
    
      cout << "Values of factors1" << endl;
      for ( int i = 0; i < factors1.size( ); ++i )
      {
        cout << setw( 4 ) << i << setw( 15 ) << factors1[i] << endl;
      }
      cout << "------------------------------------------" << endl;
    
      cout << "Values of factors2" << endl;
      for ( int i = 0; i < factors2.size( ); ++i )
      {
        cout << setw( 4 ) << i << setw( 15 ) << factors2[i] << endl;
      }
    
      return 0;
    }
    

提交回复
热议问题