如何声明和设置类型为std::array<T, ?>(具有未定义大小)的模板类AClass的成员变量?实际std::array将在构造函数中创建,其中数组的大小是构造函数参数.
在伪C++代码中:
template <typename T> class AClass {
protected:
std::array<T, ?>* array;
public:
AClass(int n) {
this->array = new std::array<T, n>;
}
}
Run Code Online (Sandbox Code Playgroud)
正确的代码怎么样?
Bjö*_*lex 14
不要使用std::array,使用std::vector.a的大小std::array必须是编译时常量.如果要在构造函数中传递它,则需要使用a std::vector.
实际
std::array将在构造函数中创建,其中数组的大小是构造函数参数.
std::array必须在编译时知道a的大小,在你的情况下它不是.
你必须使用std::vector它.
除了使用std::vector在运行时真正定义大小的位置之外,您还可以选择在编译时指定大小(例如,根据您的问题指定为最大可能值)并将模板参数“传播”到您的类的客户端,即
template <typename T, std::size_t n>
class AClass {
protected:
std::array<T, n> array;
public:
AClass() {
// nothing to do
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
AClass<int, 5> myAClass;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3882 次 |
| 最近记录: |