I have this template function:
template <class P>
double Determinant(const P & a, const P & b, const P & c) {
return (b.x-a.x)*(c.y-a.y) - (c.x-a.x)*(b.y-a.y);
}
but I want to avoid forcing the return type to double all the time — P::x and P::y could be ints too, and I need this function in both situations. Is there a way to specify the type of x and y, something like this?
//doesn't compile; can't deduce template argument for T
template <typename T, class P>
T Determinant(const P & a, const P & b, const P & c) {
return (b.x-a.x)*(c.y-a.y) - (c.x-a.x)*(b.y-a.y);
}
edit: My compiler is VC2005
edit2: sorry to forget to mention: Unfortunately I can’t modify the implementation of the structs for P; one of the point types I deal with is MFC/ATL’s CPoint, which are hard-coded as { long x; long y; }.
Compiler cannot deduce return-type of function template, from function argument. Type deduction is done with function arguments only.
In C++03, you can define typedef in your class as:
And then you’ve to re-write your function as:
Notice the return-type now, its a dependent type. Its :
The keyword
typenameis required here.Alright, as you said you can’t modify your structs, then you can use traits instead. Here is how this can be done:
And your function template would look like this:
Notice the return-type; its slightly different now:
Again,
value_typeis a dependent name, so the keywordtypenameis required.Note that you’ve to specialize
PTraits<>for each type which you pass to the function template, as I did.