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

Unable to define a list of variable type and size using template arguments

本文关键字:类型 列表 变量 定义 参数      更新时间:2023-10-16

我有一个列表作为一个类的私有成员,该类有两个模板参数: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
      }
};

在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