相关疑难解决方法(0)

在运行时获取模板元编程编译时常量

背景

考虑以下:

template <unsigned N>
struct Fibonacci
{
    enum
    {
        value = Fibonacci<N-1>::value + Fibonacci<N-2>::value
    };
};

template <>
struct Fibonacci<1>
{
    enum
    {
        value = 1
    };
};

template <>
struct Fibonacci<0>
{
    enum
    {
        value = 0
    };
};
Run Code Online (Sandbox Code Playgroud)

这是一个常见的例子,我们可以将Fibonacci数的值作为编译时常量:

int main(void)
{
    std::cout << "Fibonacci(15) = ";
    std::cout << Fibonacci<15>::value;
    std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

但是你显然无法在运行时获得该值:

int main(void)
{
    std::srand(static_cast<unsigned>(std::time(0)));

    // ensure the table exists up to a certain size
    // (even though the rest of the code …
Run Code Online (Sandbox Code Playgroud)

c++ templates runtime metaprogramming

43
推荐指数
2
解决办法
2万
查看次数

标签 统计

c++ ×1

metaprogramming ×1

runtime ×1

templates ×1