如何获得阶乘<a>....factorial<b> at runtime?

时间:2019-04-05 21:49:03

标签: c++ templates lookup-tables

I want to fill a look up table with integers computed at compile time:

#include <iostream>
#include <type_traits>

template <int x> using number = std::integral_constant<int,x>;    
template <int n> struct factorial : number<n * factorial<n-1>::value> {};
template <> struct factorial<0> : number<1> {};

int get_factorial(int x) {
    if (x < 1) return -1;
    if (x > 5) return -1;
    static constexpr int lookup_table[] = { 
        factorial<1>::value,
        factorial<2>::value,
        factorial<3>::value,
        factorial<4>::value,
        factorial<5>::value
    };
    return lookup_table[x-1];
}

int main() {        
    int x;
    std::cin >> x;
    std::cout << get_factorial(x) << "\n";
}

This is fine for small number of elements, but what can I do when the look up table contains a large number of elements? How to populate the array without writing each element explicitly?

The factorial is only for the example. In a more realistic scenario I would like to store ~1000 elements in the lookup table.

2 个答案:

答案 0 :(得分:3)

对于C ++ 14,您可以使用std::integer_sequence

template <int... S>
constexpr std::array<int, sizeof...(S)> get_lookup_table_impl(std::integer_sequence<int, S...>)
{
    return { factorial<S>::value... };
}

template <int S>
constexpr auto get_lookup_table()
{
    return get_lookup_table_impl(std::make_integer_sequence<int, S>{});
}

请参阅完整的示例here

诀窍是std::make_integer_sequence<int, S>{}将创建std::integer_sequence<int, S...>的实例。因此,辅助函数get_lookup_table_impl可以推导其参数包。然后,factorial<S>::value...解压缩并将S的每个值传递到factorial。用花括号覆盖,可以用来初始化任何类型的std容器。我使用了std::array,但是您可以使用任何您想要的东西。

答案 1 :(得分:1)

可以在此处使用用于数组初始化的参数包扩展:

#include <iostream>
#include <type_traits>
#include <utility>
template <int x> using number = std::integral_constant<int,x>;    
template <int n> struct factorial : number<n * factorial<n-1>::value> {};
template <> struct factorial<0> : number<1> {};

template<std::size_t... Is>
int get_factorial_impl(int x,std::index_sequence<Is...>)
{
    if (x < 1) return -1;
    if (x > 5) return -1;
    static constexpr int lookup_table[] = { factorial<Is+1>::value...};
    return lookup_table[x-1];
}

int get_factorial(int x)
{
    return get_factorial_impl(x,std::make_index_sequence<5>{});
}

int main() {        
    int x;
    std::cin >> x;
    std::cout << get_factorial(x) << "\n";
}