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

时间:2015-12-18 15:22:09

标签: c++ function static const init

我有一个模板类,其中一些整数作为参数。需要根据参数计算此类的一个静态const整数(称为Length)。计算确实需要一个循环(据我所知),所以一个简单的表达式不会有帮助。

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

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

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

1 个答案:

答案 0 :(得分:2)

使用元编程。从cppreference.com

获取的C ++ 11 enable_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;
}