2015-04-05 48 views
0

我想在每次處理for循環時加倍值。我有以下代碼至今:需要一個constexpr來使for循環的值加倍

constexpr size_t doubleN(size_t n, size_t iteration) 
    { 
     return n * iteration; 
    }; 

    const array<size_t, 9> iterationArray = { 1, 2, 3, 4, 5, 6, 7, 8, 10 }; 
    for (size_t i = 1; i <= 10; i++) 
    { 
     Insertionsort<double, doubleN(INITIAL_SIZE_N_INSERTIONSORT, iterationArray[i])> insertionsort; 
     Util<doubleN(INITIAL_SIZE_N_INSERTIONSORT, iterationArray[i])> util; 
     array<double, doubleN(INITIAL_SIZE_N_INSERTIONSORT, iterationArray[i])> arrayRef; 
     util.generateRandomDoubleArray(arrayRef); 
     util.overwriteProcessorCache(); 

     cout << "Measure Insertionsort version 1 with n = " << INITIAL_SIZE_N_INSERTIONSORT << "." << endl; 
     util.startTimeMeasure(); 
     insertionsort.sortVersion1(arrayRef); 
     util.stopTimeMeasure(); 
     cout << "Measureing Insertionsort version 1 successful." << endl; 
    } 

我的問題是,我不能增加一倍的constexpr返回的值,導致其總是需要一個恆定值作爲參數。竇你有任何想法如何得到一個constexpr,總是返回一個價值,加倍前一倍的價值?

+2

'i'是一個運行時變量,所以你不能在一個常量表達式中使用它。 – Barry 2015-04-05 15:39:29

回答

4

首先,打開運行時i參數到編譯時間值:

template <std::size_t I> 
void foo() 
{ 
    Insertionsort<double, doubleN(INITIAL_SIZE_N_INSERTIONSORT, I)> insertionsort; 
    Util<doubleN(INITIAL_SIZE_N_INSERTIONSORT, I)> util; 
    array<double, doubleN(INITIAL_SIZE_N_INSERTIONSORT, I)> arrayRef; 
    util.generateRandomDoubleArray(arrayRef); 
    util.overwriteProcessorCache(); 

    cout << "Measure Insertionsort version 1 with n = " << INITIAL_SIZE_N_INSERTIONSORT << "." << endl; 
    util.startTimeMeasure(); 
    insertionsort.sortVersion1(arrayRef); 
    util.stopTimeMeasure(); 
    cout << "Measureing Insertionsort version 1 successful." << endl; 
} 

然後做一個循環:

template <size_t ... Is> 
void foos() 
{ 
    int dummy[] = {0, (foo<Is>(), 0)...}; 
    (void) dummy; // avoid warning for unused variable 
} 

或用C++ 17倍表達:

template <size_t ... Is> 
void foos() 
{ 
    (foo<Is>(), ...); 
} 

並且將其命名爲:

foos<1, 2, 3, 4, 5, 6, 7, 8, 9, 10>(); 
相關問題