c++ - std::vector 初始化的模板参数

有一个名为 Matrix 的结构,它有一个模板参数 Ndata_ 字段:

#include <cstddef>
#include <vector>

template <std::size_t N>
struct Matrix {
    std::vector<std::vector<int>> data_{N, std::vector<int>(N)};
};

为什么不能使用圆括号初始化data_

std::vector<std::vector<int>> data_(N, std::vector<int>(N));

这是错误:

<source>:6:41: error: unknown type name 'N'
    std::vector<std::vector<int>> data_(N, std::vector<int>(N));
                                        ^
<source>:6:61: error: declaration of 'N' shadows template parameter
    std::vector<std::vector<int>> data_(N, std::vector<int>(N));
                                                            ^
<source>:4:23: note: template parameter is declared here
template <std::size_t N>

最佳答案

Default member initializer (C++11 起)不支持圆括号初始化器,只支持花括号初始化器和等号初始化器。

Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

除了你已经展示的支撑之外,你还可以

template <std::size_t N>
struct Matrix {
    std::vector<std::vector<int>> data_ = std::vector<std::vector<int>>(N, std::vector<int>(N));
};

https://stackoverflow.com/questions/65458163/

相关文章:

arrays - 从 C 中的数组中删除给定数字的所有出现

java - 问题启动 Cassandra。 Java 运行时环境 : 检测到 fatal erro

reactjs - 用于本地状态管理的 Apollo Client 3.0 或 Redux?

java - 在 java.time 中,为什么 WeekFields.SUNDAY_START 会

r - 添加一列显示前两列是否包含 0

python - 模块未找到错误 : No module named 'psycopg2' in i

aws-cloudformation - AWS Proton 与 CloudFormation

powershell - 如何显示使用扩展参数调用的命令行

r - 根据条件为每个 ID 创建不同数量的行

python - numpy/pandas 向量化自定义 for 循环