I have been trying to understand this code
template <typename T, typename _Prd = equal_to<T> >
struct Vector3
{
protected:
T i,j,k;
_Prd comp;
public:
//default constructor
Vector3(void);
//explicit constructor
Vector3(const T& ijk);
//explicit constructor
Vector3(const T& i,const T& j,const T& k);
//copy constructor
Vector3(const Vector3<T,_Prd>& copy_from);
//getters
T I() const;
T J() const;
T K() const;
//setters
void I(const T& i);
void J(const T& j);
void K(const T& k);
//get magnitude of vector.
T Magnitude() const;
//angle between I,J (clockwise)
T Direction() const;
//angle between K and I,J
T Elevation() const;
//scale vector to 1
Vector3<T,_Prd>& Normalize();
//vector scale up-to value
Vector3<T,_Prd>& Scale(const T& length);
...
};
I can’t understand first statement
template <typename T, typename _Prd = equal_to<T> > struct Vector3 {};
It’s about the usage of equal_to<T>, I found the reference from here and here. But still there isn’t anything like this. Thank you for any help to make me understand this part.
Update:
After seeing the answers and reading some text book, my question turns to 2 aspects.
1. Default Template Arguments
In C++11 we can supply default template arguments to a template.
Example from C++ primer 5th ed. Page 670.
#include <functional>
template <typename T, typename F = less<T> >
int compare (const T &v1, const T &v2, F f = F() )
{
if (f(v1, v2) return -1 ;
if (f(v2, v1) return 1 ;
return 0 ;
}
And then we use this template as:
bool i = compare(0,42) ;
The template will use default less function-object class to instantiate.
However, when we use our own objects:
Sales_data item(cin), item2(cin) ;
bool j = compare (item, item2, compareIsbn) ;
Then F turns to compareIsbn function-object instead.
So that the same happens on my question above, this way will leave an entrance to the user of the template to allow them introducing their own function-object, in this case it is used as comparator.
2. Predicates
std::equal_tois a class template, which provides something like this:In other words, it’s a function-object class that wraps the ordinary
==comparator. The point is thatequal_tocan be specialized, and thus provides a non-intrusive way of adding customizability.On top of that, your template
Vector3also provides an intrusive way of customizing the comparator by way of the second template argument.Note that predicates are typically objects, and not just trait classes. So your container will actually contain a predicate subobject. If the predicate class is default-constructible, this is no problem, but if it isn’t then you must normally provide a copy of the predicate in the container constructor.
As a homework assignment, you can think about how you can avoid spending any actual memory on the predicate subobject.