What’s up guys,
I am trying to overload the addition operator for my math vector class.
My (seemingly logically correct) simplified code is:
template<typename T>
class Vector2
{
private:
T m_data[2];
template<typename U>
friend auto operator+(Vector2<T> a, Vector2<U> b) -> Vector2<decltype(a.m_data[0] + b.m_data[0])>
{
Vector2<decltype(a.m_data[0] + b.m_data[0])> ret( a.m_data[0] + b.m_data[0],
a.m_data[1] + b.m_data[1] );
return ret;
}
public:
inline Vector2(T x, T y)
{
m_data[0] = x;
m_data[1] = y;
}
};
int main()
{
Vector2<float> v1(0.5f, 0.5f);
Vector2<float> v2(1, 2);
v2 + v1; // Line 29
return 0;
}
However, GCC 4.6.1 gave me this:
W:\projects\Awesome\BetterStuff\main.cpp||In function 'Vector2<decltype ((a.m_data[0] + b.m_data[0]))> operator+(Vector2<T>, Vector2<U>) [with U = float; T = float; decltype ((a.m_data[0] + b.m_data[0])) = float]':|
W:\projects\Awesome\BetterStuff\main.cpp|5|error: 'float Vector2<float>::m_data [2]' is private|
W:\projects\Awesome\BetterStuff\main.cpp|29|error: within this context|
||=== Build finished: 2 errors, 0 warnings (0 minutes, 0 seconds) ===|
And if I changed the second vector to an int vector, it would give me more (similar) errors.
The closest I came to figuring this thing out was finding this interesting page: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=48884
But sadly, I couldn’t use it for solving my own problem.
I tried GCC 4.6.2 and 4.7.0 but my code didn’t compile either.
Changing “private” to “public” indeed solves my problem, but obviously my intention is not to expose m_data;
I just want to define an addition operator that its return type is determined by the template parameters, which from my understanding is, a compile time thing – for each instantiation of the template function, the compiler automatically figures out the return type based on the decltype() there. I mean, in which way main() is trying to access the contents of m_data for one of these vectors?
This whole thing is confusing me, any help would be greatly appreciated.
OK thanks
Well, GCC is right… The problem was not that Vector2(float) was trying to access Vector(int)’s private members, but that operator+ (which is only a friend of Vector2(float)) was trying to access Vector2(int)’s private members. So the updated code is: