【发布时间】:2013-10-02 23:37:14
【问题描述】:
简要说明:
考虑一个基于可变参数模板的类型列表,用于保存整数值:
template<typename... Ts>
struct list {};
using my_int_list = list<std::integral_constant<0>,
std::integral_constant<1>,
std::integral_constant<2>>;
这可以使用数组初始化器和可变参数包扩展转储到数组中:
template<typename LIST>
struct to_array;
template<typename... Ts>
struct to_array<list<Ts...>>
{
static constexpr unsigned int result[] = { Ts::value... };
};
现在考虑我想对二维数组做同样的事情(换句话说,输入是类型列表的类型列表)。我们可以使用后面的元函数来转储子数组,并使用第二个元函数来转储外部数组:
template<typename LIST>
struct to_2d_array;
template<typename... Ts>
struct to_2d_array<list<Ts...>>
{
using value_type = unsigned int; //To simplify things, suppose we know the type
//of the elements. Also suppose the array is
//squared.
static constexpr value_type result[sizeof...(Ts)][sizeof...(Ts)] = { to_array<Ts>::result... };
};
我的问题(即深度上下文):
我正在编写一个编译时 Mandelbrot 分形渲染。渲染工作“正常”1,并将结果作为 RGB 值的方形 2d 类型列表(相同长度的类型列表的类型列表)返回。
需要to_2d_array 元函数将结果转储到数组并在运行时将其写入 PPM 文件中。
The RGB values 是等效于std::integral_constant<unsigned int> 的完整包装器的实例,它有一个成员value 保存该值。
我上面发布的代码正是我写的in my implementation,使用标准类型(std::integral_constant)而不是我自己的类型。上面的代码完美运行at coliru,但我的编译器(GCC4.8.1)说:
初始化器需要用额外的大括号括起来。
在to_2d_array。如果我放了额外的大括号,则赋值编译会失败,并出现“从指针到数组的无效转换”。
我做错了什么?是否有其他近似值可以实现这一目标?
[1] 现在真的不行,因为编译这个模板元编程怪物会导致 GCC 内部分段错误 :)。但是这个问题和问题无关……
【问题讨论】:
标签: c++ arrays c++11 template-meta-programming typelist