gpt4 book ai didi

c++ - 将固定长度的括号括起来的初始化程序列表传递给函数

转载 作者:行者123 更新时间:2023-12-03 07:14:50 25 4
gpt4 key购买 nike

我想将括号括起来的初始化器列表传递给表示固定尺寸矩阵的类的构造函数。这是我的代码:

#include <cstddef>
#include <array>

template <typename T, size_t N, size_t M>
using array2d = std::array<std::array<T, N>, M>;

template <typename T, size_t N, size_t M>
class Matrix {
private:
array2d<T, N, M> value;
public:
Matrix(const array2d<T, N, M>& value) : value(value) {}
};

int main() {
Matrix<double, 2, 3> mat1 ({
{1, 2, 3},
{4, 5, 6}
});
}
我的假设是, array2d是从初始化程序列表自动创建的,而我将其作为构造函数的参数传递给该初始化程序,但事实并非如此,因为编译器会引发以下错误:
1704186652/source.cpp:16:23: error: no matching constructor for initialization of 'Matrix<double, 2, 3>'
Matrix<double, 2, 3> mat1 ({
^ ~
1704186652/source.cpp:8:7: note: candidate constructor (the implicit copy constructor) not viable: cannot convert initializer list argument to 'const Matrix<double, 2, 3>'
class Matrix {
^
1704186652/source.cpp:8:7: note: candidate constructor (the implicit move constructor) not viable: cannot convert initializer list argument to 'Matrix<double, 2, 3>'
class Matrix {
^
1704186652/source.cpp:12:3: note: candidate constructor not viable: cannot convert initializer list argument to 'const array2d<double, 2UL, 3UL>' (aka 'const std::__1::array<std::__1::array<double, 2>, 3>')
Matrix(const array2d<T, N, M>& value) : value(value) {}
^

最佳答案

对于初学者,您需要颠倒尺寸。

Matrix<double, 2, 3>
如果您扩展模板,则变为
std::array<std::array<double, 2>, 3>
或三个元素数组,每个元素为两个值,而不是每个元素三个值的两个元素数组。
带有嵌套构造函数和参数的支撑式初始化列表有时可能是解密的挑战,而且通常情况下,您只需要随机戳一下并随意涂抹,直到编译为止。下面的代码使用gcc 10.2进行编译,并使用调试器检查所有内容。我尽力解释大括号:
#include <cstddef>
#include <array>

template <typename T, size_t N, size_t M>
using array2d = std::array<std::array<T, N>, M>;

template <typename T, size_t N, size_t M>
class Matrix {
private:
array2d<T, N, M> value;
public:
Matrix(const array2d<T, N, M>& value) : value(value) {}
};

int main() {
Matrix<double, 2, 3> mat1({ // Initializing the 1st constructor parameter
{ // std::array< ,3> using initializer_list constructor

// Initializing std::array<T, 2>s
{1, 2},
{3, 4},
{5, 6}
},
});

return 0;
}

关于c++ - 将固定长度的括号括起来的初始化程序列表传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65005537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com