#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Location
    Manchester, England
    Posts
    39
    Rep Power
    17

    Using static modifier with template classes


    Hi,

    Does anyone have experience of the following? The member attribute counter is declared static so I can keep track of how many variables are in existence. However, this means that it isn't actually defined yet, right?

    To do that I have to declare it outside of the class. If this much is true, then the problem I'm having is getting the syntax right on the line that I've commented out, because things are confused by the template <> stuff.

    Quite new to this part of C++. Any help much appreciated!

    Code:
    // Class to store variable information.
    template <class PType> class variable
    {
      // Counter to ensure maximum limit of variables not breached.
      static int counter;
    public:
    
      // Variable name and value.
      char *name;
      PType value;
    
      // Constructors.
      variable(void);
      variable(char *n, PType v);
    };
    //int variable<PType>::counter;
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Feb 2001
    Posts
    1,474
    Rep Power
    15
    I looked it up, but it's too complicated. Search google for:

    "Static members of template classes"

    Here's an example I found:
    Code:
    template <class T> class key
    {
    public:
          static T x;
    };
    template <class T> T key<T> ::x; // template definition
    void main()
    {
          key<int>::x = 0;
    }
    Based on that, I think this might work:
    Code:
    template <class PType> class variable
    {
      static int counter;
    public:
    
      // Variable name and value.
      char *name;
      PType value;
    
      // Constructors.
      variable(void);
      variable(char *n, PType v);
    };
    
    template<class PType> int variable<PType>::counter;
    
    int main()
    {
        variable<double>::counter=0;
    ...
    ...
    ...
    }
    Last edited by 7stud; April 24th, 2003 at 06:38 AM.
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2003
    Location
    Manchester, England
    Posts
    39
    Rep Power
    17
    Magic, worked first time!

    Thanks 7stud!

IMN logo majestic logo threadwatch logo seochat tools logo