Your question, your audience. Choose who sees your identity—and your question—with question security.
template<typename T, unsigned dim>
T operator + (const T & t0[dim], const T & t1[dim])
{
T ret[dim];
for (int i=0; i<dim; i++)
ret[i] = t0[i] + t1[i];
}
template<unsigned dim>
class Vector
{
public:
Vector(double *init = NULL)
{
if (init == NULL)
memset(components, 0, sizeof(components));
else
memcpy(components, init, sizeof(components));
}
~Vector(void) {}
inline double operator[](int i) const { return components[i]; }
inline double & operator[](int i) { return components[i]; }
/*
these commented out functions are the ones I want to mimic using
templates
inline Vector<dim> operator/(double div) const
{
Vector<dim> ret;
for (int i=0; i<dim; i++)
ret[i] = components[i] / div;
}
inline Vector<dim> operator*(double mul) const
{
Vector<dim> ret;
for (int i=0; i<dim; i++)
ret[i] = components[i] * mul;
}
inline Vector<dim> operator+(Vector<dim> that) const
{
Vector<dim> ret;
for (int i=0; i<dim; i++)
ret[i] = components[i] + that[i];
}
inline Vector<dim> operator-(Vector<dim> that) const
{
Vector<dim> ret;
for (int i=0; i<dim; i++)
ret[i] = components[i] - that[i];
}
*/
inline double MagnitudeSq() const
{ return dot(*this, *this); }
inline double Magnitude() const
{ return sqrt(MagnitudeSq()); }
inline static double dot(const Vector<dim> & v0, const Vector<dim> & v1)
{
double accum = 0;
for (int i=0; i<dim; i++)
accum += v0[i]*v1[i];
return accum;
}
private:
double components[dim];
};
// This works:
template<template<unsigned> class T, unsigned dim>
T<dim> operator + (const T<dim> & t0, const T<dim> & t1)
{
T<dim> ret;
for (int i=0; i<dim; i++)
ret[i] = t0[i] + t1[i];
return ret;
}
// This should work too (template parameters are switched. nothing big):
template<unsigned dim, template<unsigned> class T>
T<dim> operator + (const T<dim> & t0, const T<dim> & t1)
{
T<dim> ret;
for (int i=0; i<dim; i++)
ret[i] = t0[i] + t1[i];
return ret;
}
// after this we can use statements like:
Displacement<3> d1, d2, d3;
d3 = d1 + d2;
Velocity<2> v1, v2, v3;
v1 = v2 + v3;
Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.
Have a better answer? Share it in a comment.
Join the community of 500,000 technology professionals and ask your questions.