gpt4 book ai didi

c++ - 初始化嵌套模板

转载 作者:太空狗 更新时间:2023-10-29 20:44:26 27 4
gpt4 key购买 nike

我正在尝试了解有关模板的更多信息,但遇到了一个我似乎无法解决的问题。目前下面的类工作正常。

#include <iostream>
#include <vector>
#include <cstring>
using namespace std;

template <class T, int s>
class myArray{
public:
T* data;
inline T& operator[](const int i){return data[i];}
myArray(){
data=new T[s];
}
myArray(const myArray& other){
data=new T[s];
copy(other.data,other.data+s,data);
}
myArray& operator=(const myArray& other){
data=new T[s];
copy(other.data,other.data+s,data);
return *this;
}
~myArray(){delete [] data;}
};

如果我使用它:

myArray<myArray<myArray<int,10>,20>,30> a;

a 现在是 30x20x10 数组,我可以使用普通数组括号访问它,例如[5][5][5]。我想添加一个功能,这样我就可以写:

myArray<myArray<myArray<int,10>,20>,30> a(10);

并将所有条目初始化为 10,例如。我不知道该怎么做。据我了解, myArray 的每一层都是使用默认构造函数构造的。如果我将其更改为:

myArray(int n=0){
data=new T[s];
fill(data,data+s,n); //T might not be of type int so this could fail.
}

我认为当数据不是 int 类型时(即在维度 > 1 的任何数组上),这应该会失败,但事实并非如此。它在数组为正方形时有效,但如果不是,则某些条目未设置为 10。有谁知道标准 vector 类如何实现这一点?任何帮助都会很棒。谢谢!

最佳答案

好吧,尝试这样的事情:

 myArray()
: data(new T[s]()) // value-initialization!
{
}

myArray(T const & val)
: data(new T[s]) // default-initialization suffices
{
std::fill(data, data + s, val);
}

如果您喜欢可变参数模板,您可能会想出一些更奇怪的东西,涉及可变填充的初始化列表,但我认为我们一周的学习已经够多了。

请注意使用 new 的根本缺陷:任一版本都要求您的类 T 可以在某些“默认”状态下实例化,它是可分配的,即使我们从不需要第二个版本中的默认状态。这就是为什么“真正的”库将内存分配和对象构造分开,并且除非是放置版本,否则您永远不会看到 new 表达式。

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

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