需要一个constexpr来使for循环中的值加倍

时间:2015-04-05 15:37:48

标签: c++ templates const 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,它总是返回一个基于先前加倍值加倍的值?

1 个答案:

答案 0 :(得分: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>();