gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:06:59 24 4
gpt4 key购买 nike

有一个名为 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));
};

关于c++ - std::vector 初始化的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65458163/

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