Clynamen
Clynamen

Reputation: 519

Template - class that uses int, short or float when necessary

I want to write a class that manages euclidean vector and that store its initial point using short, int, long or float. I thought to create a template like this:

    template<class unit> class EVector
{
private:
    unit x;
    unit y;
public:
    EVector();
    setX();
    setY();
};

So user creates an EVector choosing the suitable primitive type. But how can I implement the operation between different classes, e.g.

EVector<int> a;
EVector<float> b;

EVector<double> c;

c = a + b;  

operator= will copy the coordinates, operator+ adds them.

Upvotes: 5

Views: 1018

Answers (2)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133072

You want to enable assignment(and copy-construction) from EVector<U> to EVector<T> when Uis convertible to T

template<class T>
class EVector
{
   template<class U>
   EVector(EVector<U> const & rhs)
           :x(rhs.x), y(rhs.y)
   {
   }
   ...
}

Note that even if you have provided this templated copy-constructor, the compiler will generate a copy-constructor for you( when T is same as U). In this case you're fine with that default implementation - it does exactly what you need. But otherwise you'd have to explicitly define the nontemplated constructor(and copy-assignment) as well.

Upvotes: 2

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507105

For addition, you can use my promote implementation:

template<typename A, typename B> 
EVector<typename promote<A, B>::type>
operator +(EVector<A> const& a, EVector<B> const& b) {
  EVector<typename promote<A, B>::type> ev;
  ev.setX(a.getX() + b.getX());
  ev.setY(a.getY() + b.getY());
  return ev;
}

For types double and int, it will yield double for example.

Upvotes: 3

Related Questions