如何处理非default_constructible tyname 变量
How to handle non default_constructible tyname variables
我的问题是有人如何处理非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;
}
}
};
会没事的。
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 用"=default"声明的函数应该只在头文件中执行
- 即使设置了"__set_what_UTF8",也始终显示"Default TException."
- .value( "key" , default) 不适用于空的 json 对象吗?
- MSVC 杂注警告省略 CPP 文件中的'default'
- 由于"error C4430: missing type specifier - int assumed. Note: C++ does not support default-int",我现在无法编
- 为什么使用默认构造函数"{}"而不是"= default"存在性能变化?
- 缺少类型说明符 - 假定为 int.注意 c++ 不支持 default-int
- 什么是 Direct3D 12.0 上的"Map Default Buffer"?
- 错误:C4430:缺少类型说明符-假定为int.注意:C++不支持default-int
- c++default-int中的语法错误
- 有些时候,阶级必须"default copy c'tor" ?当我做"new Type[..]"时会发生什么?
- 有没有办法在初始化字符串时避免来自 clang-tidy(fuchsia-default-arguments)的警告?
- "No default constructor exists "即使我不需要它
- 如何解决gthr-default.h的问题?
- 为什么 "=default" 析构函数与隐式声明的析构函数不同?
- VS 2017 构建工具失败,出现错误 MSB4019:找不到导入的项目"D:Microsoft.Cpp.Default.props"
- 'default-initialization in copy-initialization context'在C++中是什么意思?
- 我的模板二叉搜索树类给出了错误"Node<T>: no appropriate default constructor available,"如何解决这个问题?
- 为什么要显式声明类特殊函数为"default"