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

标签 c++ function static constants init

我有一个以一些整数作为参数的模板类。需要根据参数计算此类的一个静态常量整数(称为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;
}

关于c++ - 使用静态函数初始化 static const int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34358813/

相关文章:

c - C中字符串文字的"Life-time"

java - 从类数组调用方法会给出 NullPointerException

Java静态变量值不能传递

java - 不是静态java接口(interface)

c++ - 英特尔线程构建 block 并发队列 : Using pop() over pop_if_present()

php - 在 PHP/C++ 中加密自定义数据包

javascript - 损坏的代码?为什么它停止工作

python - 如何在数据框的每一行上应用一个函数?

c++遍历列表以调用某个函数

c++ - 如果不需要,避免在 Make 中链接和编译