tags:

views:

97

answers:

2

I am trying to open raw data file(s) that contain some numbers using VC++. The numbers could be 8/16/24 bit. I have a prior knowledge of that for a given file.

Can I use C++ templates to create array variables to store numbers read from files based on what bit-depth they are? Something on the lines of this pseudo code:

if(BitDepth==8)
{
    CTemplate<unsigned byte> data; // data type should be unsigned byte
    Read8Bit(data);
    //.. various ops to read 8 bit data
}

if(BitDepth==16)
{
    CTemplate<unsigned short> data; // data type should be unsigned short
    Read16Bit(data);
    //.. various ops to read 16 bit data
}

if(BitDepth==24)
{
    CTemplate<unsigned int> data; // data type should be unsigned int
    Read24Bit(data);
    //.. various ops to read 24 bit data
}

//Later use 'data' out of scope of if() conditionals

Of course, the template variable 'data' has to be used outside the scope of the if() conditionals later. So I need to declare 'data' as a global (say, in header). Am loosing track here...

+1  A: 

Unless the bit depth is a compile-time constant, you have two choices:

1) use runtime-variable implementation objects (the implementations can be generated using templates rather than runtime polymorphism, but to use them you have to type erase to a virtual interface or switch on the runtime bit depth, in order to select among them).

2) make all the calling functions take the bit depth as a template parameter, up until some level where you do the above runtime variable -> particular bit depth template mapping (at least in main you'll have to do this)

Yes, you can have (constant) integer template arguments and partial specialization on them.

wrang-wrang
Thanks so much for the reply!What I would like to have is a single Template variable (an array) that can be made 8/16/24 bit in the runtime. Any suggestions on that?
In fact, I am sure that this is a standard problem. Just that I am not finding any references to a solution.
Yes, that would be fine for your template typename variable. It may be simpler to have 3 named templates with a const member (equivalently, you can have the number as the argument and partially specialize).
wrang-wrang
A: 

I would just declare data as BYTE*. Then, provide a wrapper class that will allow to retreive elements by index according to the bit depth. Having such a class, you will be able to change bit depth in runtime...

Maybe it is enough to provide a template "at" function, which accepts index and return an element of the specified type in BYTE array. Some low-level programming will be involved, but c++ is really good for that!

SadSido