0

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

#include <list>

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

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

   // More code here...

};

我的方法似乎遵循此处提供的信息和示例;但是当我编译这个时,我得到以下错误。

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

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

谢谢!

编辑:这是我修改后的更详细的来源。我现在在使用公共方法时遇到了麻烦。注意:这是我班级的头文件。

#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
      }

};
4

1 回答 1

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++ 只支持包含模块,你需要some_function在声明 my_class 的同一个文件中定义。

于 2013-02-03T07:24:08.423 回答