使用静态函数初始化 static const int

Initialise static const int with static function

我有一个模板 class,其中包含一些整数作为参数。这个class的一个static const integer(称之为Length)需要根据参数计算出来。计算确实需要一个循环(据我所知),所以一个简单的表达式无济于事。

static int setLength()
{
    int length = 1;
    while (length <= someTemplateArgument)
    {
        length = length << 1;
    }
    return length;
}

返回的长度应该用于初始化LengthLength用作固定长度的数组,所以我需要它是常量。

这个问题有解决办法吗?我知道 constexp 可以提供帮助,但我不能使用 C11 或更高版本。

使用元编程。 C++11 enable_if 的实现取自 cppreference.com

#include <iostream>

template<bool B, class T = void>
struct enable_if {};

template<class T>
struct enable_if<true, T> { typedef T type; };

template <int length, int arg, typename = void>
struct length_impl
{
    static const int value = length_impl<(length << 1), arg>::value;
};

template <int length, int arg>
struct length_impl<length, arg, typename enable_if<(length > arg)>::type>
{
    static const int value = length ;
};

template <int arg>
struct length_holder
{
    static const int value = length_impl<1, arg>::value;
};

template<int n>
struct constexpr_checker
{
    static const int value = n;
};

int main()
{
    std::cout << constexpr_checker< length_holder<20>::value >::value;
}