C++ 将可变模板内容转储到二维数组 简要说明:

C++ 将可变模板内容转储到二维数组 简要说明:,c++,arrays,c++11,template-meta-programming,typelist,C++,Arrays,C++11,Template Meta Programming,Typelist,考虑用于保存整数值的基于可变模板的类型列表: template<typename... Ts> struct list {}; using my_int_list = list<std::integral_constant<0>, std::integral_constant<1>, std::integral_constant<2>>

考虑用于保存整数值的基于可变模板的类型列表:

template<typename... Ts>
struct list {};

using my_int_list = list<std::integral_constant<0>,
                         std::integral_constant<1>,
                         std::integral_constant<2>>;
模板
结构列表{};
使用my_int_list=列表;
可以使用数组初始值设定项和变量包扩展将其转储到数组:

template<typename LIST>
struct to_array;

template<typename... Ts>
struct to_array<list<Ts...>>
{
    static constexpr unsigned int result[] = { Ts::value... };
}; 
模板
结构到数组;
模板
结构到数组
{
static constexpr unsigned int result[]={Ts::value…};
}; 
现在我想用2D数组做同样的事情(换句话说,输入是打字员的打字员)。我们可以使用后面的元函数转储子阵列,使用第二个元函数转储外部阵列:

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... };
};
模板
结构到二维数组;
模板
结构到二维数组
{
使用value_type=unsigned int;//为了简化事情,假设我们知道类型
//也假设数组是
//平方。
static constexpr value_type result[sizeof…(Ts)][sizeof…(Ts)]={to_array::result…};
};
我的问题(即深入的背景): 我正在编写编译时Mandelbrot分形渲染。渲染效果“良好”1,并将结果作为RGB值的正方形2d类型列表(相同长度类型列表的类型列表)返回。 需要使用
to_2d_array
元函数将结果转储到数组,并在运行时将其写入PPM文件

是与
std::integral_constant
等效的整数包装的实例,它有一个成员
value
,该成员保存该值

我上面发布的代码正是我所写的,使用标准类型(
std::integral\u constant
)而不是我自己的类型。上面的代码工作得很好,但我的编译器(GCC4.8.1)说:

初始值设定项需要用附加的封闭括号封闭

到\u 2d\u数组中
。如果我加上大括号,assimment编译将失败,并出现“从指针到数组的转换无效”

我做错了什么?是否有其他近似方法可以实现这一点?


[1] 实际上,它现在不起作用,因为编译这个模板元编程怪物会导致GCC内部分段错误:)。但是这个问题与这个问题无关…

根据你的文章,我想指出一些问题

  • 结果的类型

    以下代码不编译

    int main() {
      int x[] = {1, 2, 3};
      int y[3][3] = {x, x, x};
    }
    
    然而,以下情况确实如此

    #include <array>
    
    int main() {
      std::array<int, 3> x = {1, 2, 3};
      std::array<std::array<int, 3>, 3> y = {x, x, x};
    }
    
    印刷品:

    0 1 2
    
    0 1 2
    0 1 2
    0 1 2
    

    使用gcc 4.8.2、clang 3.3和Coliru上的gcc 4.8进行测试。

    您向我们展示了有效的代码,但没有展示无效的代码。请编辑您的问题并添加。@DanielFrey我提供的代码完全相同,但使用标准库的类型(即大家都知道的类型)而不是我自己的类型。@DanielFrey您也可以检查原始代码(第64行和下面的代码)似乎有效@DanielFrey您使用2d类型列表进行过尝试吗?在该示例中,您使用了1d类型列表
    0 1 2
    
    0 1 2
    0 1 2
    0 1 2