我想用在编译时计算的整数填充一个查找表:
#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";
}这对于少量的元素是很好的,但是当查找表包含大量的元素时,我该怎么办?如何在不显式编写每个元素的情况下填充数组?
factorial仅用于示例。在一个更现实的场景中,我希望在查找表中存储大约1000个元素。
发布于 2019-04-06 06:04:07
在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,但是你可以使用任何你想要的东西。
发布于 2019-04-06 06:06:03
可在此处使用用于数组初始化的参数包扩展:
#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";
}https://stackoverflow.com/questions/55543776
复制相似问题