views:

50

answers:

3

Hi there, I have function which takes in an parameter of a class called "Triple", and am returning the averge of 3 values of type float.

template <typename ElemT>
float average(Triple ElemT<float> &arg){
    float pos1 = arg.getElem(1);
    float pos2 = arg.getElem(2);
    float pos3 = arg.getElem(3);

    return ( (pos1+pos2+po3) /3 );
}

when i try compiling this i get

q2b.cpp:32: error: template declaration of `float average'
q2b.cpp:32: error: missing template arguments before "ElemT"

not quite sure what this means.

+5  A: 

The declaration of the function parameter uses wrong syntax. Maybe you meant to write this:

template <typename ElemT>
float average(Triple<ElemT> &arg){
  ...
}

Or, if the function should just be specific to Triples of floats:

float average(Triple<float> &arg){
  ...
}
sth
sil3nt
@sil3nt: yes, if you just want it for floats, that's correct (edited that into my answer)
sth
thanks, Do I still need to use the `template <typename ElemT>` before that even when its specific to floats?
sil3nt
@sil3nt: No, you don't need the `template<...>` anymore for the function definition, since there are no generic template parameters left "unspecified" (as opposed to the first alternative in my answer, where it would still be undecided what type `ElemT` ends up to be). `average` is just a normal function operating on `Triple<float>`, it doesn't need to be a template itself.
sth
A: 

Triple ElemT<float> &arg is not a valid type

Do you mean Triple<ElemT> &arg?

R Samuel Klatchko
And why bother with the template argument? How about just Triple<float>?
Duracell
yeah thats what I was lost in, you are right i wanted Triple<float>
sil3nt
A: 

Right now, it's not clear what you intend the template parameter to mean. It appears that a non-template function should work fine:

float average(Triple const &arg) {
    return (arg.getElem(1) + arg.getElem(2) + arg.getElem(3)) / 3.0f;
}

If Triple is itself a template that can be instantiated over different possible types, you could do something like this:

template <class T>
T average(Triple<T> const &arg) { 
    return (arg.getElem(1) + arg.getElem(2) + arg.getElem(3)) / T(3.0);
}
Jerry Coffin