【问题标题】:Nesting variadic template嵌套可变参数模板
【发布时间】:2019-02-05 06:50:40
【问题描述】:

我有两个使用初始化列表的类。一个是 Vector 样式的类,它包含一个值列表。

Vec.h:

template< typename T, int nDimensions = 2 >
class Vec{
    private:
        std::array< T, nDimensions > elements_;
    public:
        template <typename... U>
        Vec(U... ts) : elements_{ ts... } {}
}

那么当使用时:

typedef Vec< int, 2 > Vec2i;
Vec2i twoi = { 1,2 };
Vec2i twoi2 = twoi; //I have copy constructor and other methods finished. 

这个类工作得很好而且很花哨,但是当我尝试将这个类与我的 Matrix 样式类一起使用时,我无法找出它的构造函数的正确语法。

template< typename T, int X,int Y>
class Mat {
   private:
     std::array< Vec<T, X>, Y > elements_;
}

我喜欢这样使用它:

typedef Mat<int, 3,3> Mat3i;
Mat3i threemat = {  {1,2,3},
                    {4,5,6},
                    {7,8,9}};

现在,iv 尝试使用初始化列表作为构造函数并取得了一些成功,但我无法弄清楚传递子列表的语法。

Mat(std::initializer_list<Vec<T, X>> values) {
    for (auto& t : values) {
        //What goes here?
    }
}

我也尝试过迭代列表并手动分配它们,但那是不行的。

还值得注意的是,这些类具有用于列表的连续内存块,并且没有其他变量,这一点很重要。否则,我将使用其他类型而不是 std::array。 (用于铸造和联合目的。)

我正在争论是否需要将每个值重新解释为 Vec 然后复制这些值。

【问题讨论】:

    标签: c++ nested variadic-templates


    【解决方案1】:

    作为替代:

    Mat(std::initializer_list<Vec<T, X>> values) {
        std::copy(values.begin(), values.end(), elements_.begin());
    }
    

    【讨论】:

    • 这也很有效,可能是更好的答案。一个小问题,您如何使用这种方法防止缩小/扩大转化?
    【解决方案2】:

    我是个白痴。

    Mat(std::initializer_list<Vec<T, X>> values) {
        int i = 0;
        for (auto& t : values) {
            elements_[i++] = t;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      相关资源
      最近更新 更多