使用static函数初始化static const int

Initialise static const int with static function

本文关键字:static int const 函数 使用 初始化      更新时间:2023-10-16

我有一个模板类,其中包含一些整数作为参数。这个类的一个静态常量整数(称为Length)需要根据参数进行计算。计算确实需要一个循环(据我所知),所以简单的表达式没有帮助。

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

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

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

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

#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;
}