gpt4 book ai didi

c++ - 无法使用模板参数定义变量类型和大小的列表

转载 作者:行者123 更新时间:2023-11-28 03:23:55 25 4
gpt4 key购买 nike

我有一个列表作为一个类的私有(private)成员,它有两个模板参数:type 用于列表元素的数据类型,size 用于元素数量在列表中。为此,我想使用我的两个模板参数来使用列表的填充构造函数。这是我的尝试:

#include <list>

template <typename type, unsigned int size>
class my_class {

private:
std::list<type> my_queue(size, 0);

// More code here...

};

我的方法似乎遵循提供的信息和示例 here ;但是当我编译它时,出现以下错误。

error: 'size' is not a type
error: expected identifier before numeric constant
error: expected ',' or '...' before numeric constant

它似乎通过其默认构造函数而不是填充构造函数来识别列表的声明。谁能帮我解决这个问题?

谢谢!

编辑:这是我修改后的源代码,包含更多细节。我现在在使用公共(public)方法时遇到了麻烦。 注意:这是我类(class)的头文件。

#include <list>

template <typename T, unsigned int N>
class my_class {

private:

std::list<T> my_queue;

public:

// Constructor
my_class() : my_queue(N, 0) { }

// Method
T some_function(T some_input);
// The source for this function exists in another file.

};

编辑 2: 最终实现...谢谢 @billz!

#include <list>

template <typename T, unsigned int N>
class my_class {

private:

std::list<T> my_queue;

public:

// Constructor
my_class() : my_queue(N, 0) { }

// Method
T some_function(T some_input){
// Code here, which accesses my_queue
}

};

最佳答案

在C++11之前只能在构造函数中初始化成员变量,最好使用大写字符作为模板参数:

template <typename T, unsigned int N>
class my_class {
public:
my_class() : my_queue(N, 0) { }

private:
std::list<T> my_queue;

// More code here...

};

编辑:

T some_function(T some_input); C++ 只支持 inclusive-module,你需要在声明 my_class 的同一个文件中定义 some_function

关于c++ - 无法使用模板参数定义变量类型和大小的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14670326/

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