The access privileges of class templates can be a little confusing.
Say you have a simple class template.
template <typename T>
class A
{
public:
A() {}
private:
T data;
};
When you create instances of A
using,
A<int> a1;
A<float> a2;
You are defining two classes using the template. It's as if you had two classes:
class AInt
{
public:
AInt() {}
private:
int data;
};
and
class AFloat
{
public:
AFloat() {}
private:
float data;
};
It's easy to see that AInt
doesn't have access to the private section of AFloat
and vice versa.
That is also true with A<int>
and A<float>
.
In order for you make your operator+
function work, you have two choices:
- Make the members of the class template public.
Have a friend declaration like:
template <class T> class ThreeVector { private: T mx; T my; T mz; public: ThreeVector<T>(T, T, T); template <class X> ThreeVector<T> operator+(const ThreeVector<X>&); template <class X> friend class ThreeVector; };