从可变参数模板数组引用构造函数初始化双嵌套std :: array [英] initialize double nested std::array from variadic template array reference constructor

查看:73
本文介绍了从可变参数模板数组引用构造函数初始化双嵌套std :: array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Matrix 类,它可以进行一些数学运算.它把数据保存在一个双嵌套的 std :: array 中作为变量.我有一个构造函数,将数组引用作为可变参数模板.我这样做是为了让我可以更轻松地添加一些SFINAE(在此省略).

I have a Matrix class that is able to do some math. It holds its data in a double nested std::array as a variable. I have a constructor that takes an array reference as a variadic template. I did this so i could add some SFINAE more easily (omitted here).

#include <array>

template <std::size_t N, std::size_t M, typename T>
class Matrix{
  public:

    template <typename... TArgs>
    Matrix(TArgs const(&&... rows)[M]) {
        // ??
    }

  // ...

  private:
    std::array<std::array<T,M>, N> data;
};

问题

如何初始化构造函数内部的双嵌套数组?

Question

How can i initialize the double nested array inside the constructor?

推荐答案

具有未显示的约束,而不是 sizeof ..(TArgs)== N ,类型为 T ,您可以将行地址存储在数组指针中,然后正常工作

With the not shown constraint than sizeof..(TArgs) == N and types are T, you might store address of rows in array pointer and then work normally

template <typename... TArgs>
Matrix(TArgs const(&&... rows)[M]) {
    using Arr = const T (*)[M];
    const Arr args[N] = {&rows...}; // or const T (*args[N])[M] = {&rows...};

    for (std::size_t i = 0; i != N; ++i) {
        for (std::size_t j = 0; j != M; ++j) {
            data[i][j] = (*args[i])[j];
        }
    }
}

演示

这篇关于从可变参数模板数组引用构造函数初始化双嵌套std :: array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆