如何处理非default_constructible tyname 变量

How to handle non default_constructible tyname variables

本文关键字:default constructible tyname 变量 何处理 处理      更新时间:2023-10-16

我的问题是有人如何处理非default_constructible变量。我在一次测试中遇到了这个问题,并让我思考。请找到以下示例以完全理解:

template<typename W>
class Foo {
array<W> arr;
public:
void fooFunc(W const& value){
// I wanted to do the below assignment which seemed to be the wrong thing
for (int i = 0; i < 10; i++)
{
arr[i] = value;
}
}
};

从上面的代码中,我被告知第arr[i] = value;行无效,因为我认为该值是默认可构造的。所以我的问题是,我怎么能处理这个案子?

--编辑1-- 我也希望你能向我推荐任何资源,以提高我的c ++技能。任何书籍,教程等都会很出色

std::array<W>不会编译,因为它需要两个模板参数。

std::array<W, 2>(例如(将创建一个变量,其中包含两个默认构造的W类型的值。如果W不是默认构造的,这将无法编译。

下面的伪代码将创建一个包含两个类型为W的元素的vector,即使W不是默认可构造的。

std::vector<W> v;
v.emplace_back(/* some parameters used to construct a W*/);
v.emplace_back(/* some parameters used to construct another W*/);

在代码中,如果打算定义类模板 std::array 的专用化类型的非静态数据成员,则应将其声明为以下内容:

#include <array>
template<typename W,std::size_t N>
class Foo {
std::array<W,N> arr;
public:
void fooFunc(W const& value){
for (int i = 0; i < 10; i++)
{
arr[i] = value;
}
}
};

会没事的。