Sign in to follow this  

template question

This topic is 4824 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am trying to write a function that calculates some statistical information for a given array of data. The array can be of either byte, short int, or float data type. I am not good with templates, but I figured it was probably the best way to implement my routine. However, I'm getting compiler errors every time because of some problem with my syntax, so if someone could explain that'd be great.
template <class T>
void CalcStats(T *data, int dataTypeSize, int length)
{
    //  DO STUFF IN HERE
}

int main()
{
    BYTE *byteD = new BYTE[size];
    short int *intD = new short int[size];
    float *floatD = new float[size];

    CalcStats(byteD, 1, size);
    CalcStats(intD, 2, size);
    CalcStats(floatD, 4, size);
}

Share this post


Link to post
Share on other sites
1) What is the error?
2) Where is size defined? Is it a constant?
3) There is no need for a dataTypeSize parameter, this will only create the possibility for mistakes, problems porting, etc. If you need the size just use sizeof(T)

Share this post


Link to post
Share on other sites
[Linker Error] Unresolved external 'void CalcStats<unsigned char>(unsigned char *, long, int, Statistics *, int)' referenced from C:\PROGRAM FILES\BORLAND\CBUILDER6\PROJECTS\WINBOXER CURRENT\UEMDATA.OBJ

[Linker Error] Unresolved external 'void CalcStats<short>(short *, long, int, Statistics *, int)' referenced from C:\PROGRAM FILES\BORLAND\CBUILDER6\PROJECTS\WINBOXER CURRENT\UEMDATA.OBJ

[Linker Error] Unresolved external 'void CalcStats<float>(float *, long, int, Statistics *, int)' referenced from C:\PROGRAM FILES\BORLAND\CBUILDER6\PROJECTS\WINBOXER CURRENT\UEMDATA.OBJ


You will notice that the function arguments are not the same as in the original post. That is because I was just writing an example earlier. The real function is:

template <class T>
void CalcStats(T *data, long size, int length, Statistics *stats, int dataFormat);

Share this post


Link to post
Share on other sites
Put the implementation of calcstats in the header file, not the cpp file.

Otherwise you need to specifically instantiate versions of CalcStats for each type you want it to operate on, which is generally a bit of a pain.

Share this post


Link to post
Share on other sites

This topic is 4824 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this