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

标签 c++ templates

我有一个列表作为一个类的私有(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/

相关文章:

c++ - 是否可以毫无异常(exception)地进行 RAII?

c++ - 模板函数的默认类型假设

c++ - 在 C++ 中从函数返回中引用运算符 & 的使用

c++ - 如何避免有关可能丢失数据的警告?

c++ - 为什么我不能将引用作为函数参数传递给std::async

c++ - 为什么我不能在 C++ 中使用模板化类型定义?

c++ - 为什么必须在何处以及为什么要放置"template"和"typename"关键字?

c++ - 模板哈希表

templates - 模板表达式的默认参数

c++ - 无论情况如何,字符串比较的小于运算符都会产生相同的结果