Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 315
Clynamen Avatar asked Jul 17 '11 07:07

Clynamen


1 Answers

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.

like image 118
Johannes Schaub - litb Avatar answered Sep 29 '22 07:09

Johannes Schaub - litb