wookie1
wookie1

Reputation: 511

operator overloading with templates

I have a class which must be able to hold a type of float, double, long excetera. I would like to overload it in such a way that it can add two instances holding different types.

template <typename T>
class F{
public:
       F(const T & t){a=t;}
       T a;
       F & operator+= (const F & rhs);
}

template<typename T>
F<T> F::operator+= (const F & rhs){
       a+=rhs.a;
       return *this

This is just pseudo code I've kept out irrelevant bits where I'm actually trying to use this sort of solution.

Now when trying to use:

  F<int> first(5);
  F<int> second(4);
  first+=second; // Works

  F<int> third(5);
  F<float> fourth(6.2);
  fourth+=third; // wont work

I can see why this doesn't work as it assumes the rhs argument is the same type as the lhs. I can also see there are potential problems in performing an operation which is int += long as if the long is big the type would need changing. What I can't seem to find is a nice way to solve the problem. I would appreciate your inputs. Thanks

Upvotes: 3

Views: 181

Answers (3)

Seth Carnegie
Seth Carnegie

Reputation: 75150

You need to make operator+= a template as well:

template <typename T>
class F{
public:
       F(const T & t){ a = t; }
       T a;

       template<typename T2>
       F& operator+=(const F<T2>& rhs);
}; // semicolon was missing

template<typename T>
template<typename T2>
F<T>& F<T>::operator+=(const F<T2>& rhs) {
       a += rhs.a;
       return *this; // semicolon was missing
} // brace was missing

Then you can do

F<int> a(4);
F<float> b(28.4);

b += a;

cout << b.a << endl; // prints 32.4

Here is a working example.

Upvotes: 7

moka
moka

Reputation: 4501

    template <typename T>
    class F{
    public:
           F(const T & t){a=t;}
           T a;
           template<typename T2>
           F & operator+= (const F<T2> & rhs);
    };

    template<typename T>
    template<typename T2>
    F<T>& F<T>::operator+= (const F<T2> & rhs){
           a+=(T)rhs.a;
           return *this
    }

EDIT:

fixed error, see comments

Upvotes: 1

John Dibling
John Dibling

Reputation: 101494

You can templatize operator+=:

template<typename G> F<T> & operator+= (const F<G> & rhs);

...assuming you can somehow convert a G to a T.

Upvotes: 0

Related Questions