我有一个列表作为一个类的私有成员,它有两个模板参数:type
表示列表元素的数据类型,size
表示列表中元素的数量。为此,我想使用我的两个模板参数来使用list的fill构造函数。这是我的尝试:
#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
似乎它通过默认构造函数而不是fill构造函数来识别列表的声明。任何人都可以帮我解决这个问题吗?
谢谢!
编辑:这是我修改过的来源,详细信息。我现在遇到了公共方法的问题。 注意:这是我班级的头文件。
#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
}
};
答案 0 :(得分:2)
你只能在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 ++只支持包含模块,您需要在声明my_class的同一文件中定义some_function
。