[C++ TEMPLATE] Static variable inside a templated function

Discussion in 'C Programming' started by LiloLilo, Jun 6, 2010.

  1. LiloLilo

    LiloLilo Guest

    Hi all,

    the following function writes n bits data to file. Parameter named
    'Data' contains the value to be written, 'Length' contains the number
    of bits of 'Data' to write. This function uses a static buffer named
    BitBuffer to store bits between calls. When BitBuffer is full it is
    written to file.

    void WriteBitsToFile(unsigned Data, unsigned Length, std::eek:fstream &
    OutFile) {

    static unsigned BitBuffer = 0; static unsigned BitCounter = 0;


    for (unsigned i = Length; i --; ) {

    (BitBuffer <<= 1) |= ((Data >> i) & 0x1); BitCounter ++;

    if (BitCounter == 32) { OutFile.write((char *) & BitBuffer,
    sizeof(BitBuffer)); BitCounter = 0; }
    }

    TotalBitCounter += Length;
    }

    The function works fine, but if I change 'Data' to a templated
    variable, BitBuffer gets flushed to 0 at every call, so it does not
    retains values between calls. Please note that calls are made always
    with the same type for T2 (int) so if I am not wrong it would retain
    the value but it doesn't. Why?

    template <typename T2> void WriteBitsToFile(T2 Data, unsigned Length,
    std::eek:fstream & OutFile) {

    static unsigned BitBuffer = 0; static unsigned BitCounter = 0;


    for (unsigned i = Length; i --; ) {

    (BitBuffer <<= 1) |= ((Data >> i) & 0x1); BitCounter ++;

    if (BitCounter == 32) { OutFile.write((char *) & BitBuffer,
    sizeof(BitBuffer)); BitCounter = 0; }
    }

    TotalBitCounter += Length;
    }

    Thank you all for help.
     
    LiloLilo, Jun 6, 2010
    #1
    1. Advertising

  2. LiloLilo

    Seebs Guest

    Your question is about C++. You have posted in a newsgroup which is not
    about C++. I urge you to consider posting your question in comp.lang.c++.

    > Thank you all for help.


    Glad to be of service.

    -s
    --
    Copyright 2010, all wrongs reversed. Peter Seebach /
    http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
    http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
     
    Seebs, Jun 6, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. RA Scheltema
    Replies:
    3
    Views:
    423
    RA Scheltema
    Jan 6, 2004
  2. Amadeus W. M.
    Replies:
    2
    Views:
    414
    Amadeus W. M.
    Jul 4, 2006
  3. Thormod Johansen
    Replies:
    3
    Views:
    337
    Thormod Johansen
    Apr 19, 2007
  4. David Sanders
    Replies:
    4
    Views:
    439
    David Sanders
    Oct 30, 2007
  5. chhenning
    Replies:
    5
    Views:
    382
    chhenning
    Feb 13, 2008
Loading...

Share This Page