tomocafe
tomocafe

Reputation: 1544

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

I have a list as a private member of a class that has two template arguments: type for the data type of the list elements and size for the number of elements in the list. To this end, I want to use the list's fill constructor using my two template arguments. Here is my attempt:

#include <list>

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

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

   // More code here...

};

My approach seems to follow the information and example provided here; but when I compile this, I get the following error.

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

It seems as though it recognizes the declaration of the list by its default constructor instead of the fill constructor. Can anyone help me solve this?

Thank you!

Edit: here is my revised source with more detail. I am now having trouble with the public method. Note: this is my class's header file.

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

};

Edit 2: Final implementation... thank you, @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
      }

};

Upvotes: 0

Views: 82

Answers (1)

billz
billz

Reputation: 45410

You could only initialize member variable in constructor before C++11, better use uppercase character as template argument:

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...

};

Edit:

T some_function(T some_input); C++ only supports inclusive-module, you need to define some_function in the same file as my_class is declared.

Upvotes: 2

Related Questions