1
votes

I am trying to convert a math library written with VS so it will compile though GCC. The trouble is, I have a lot of overloaded operators that look like this:

template<typename T>
inline quaternion<T> operator+(quaternion<T> &a, quaternion<T> &b)
{return quaternion<T>(a.x+b.x,a.y+b.y,a.z+b.z,a.w+b.w);}

and so on.

The problem is: These operators were designed under the assumption that other compilers would support the automatic intermediates created for expressions like the following:

...
quaternion<T> q = log(exp(q0)*t);
...

Without them, the above would need to turn into:

...
quaternion<T> tmp = exp(q0);
tmp *= t;
quaternion<T> q = log(tmp);
...

And this is just a simple example. Some of the expressions within the systems that use this library would expand to several hundreds of lines -- something quite unpleasant considering that the overhead involved in debugging assembly-style numerics code for, say, a single function that stretches over 600 lines is astronomical in the least.

It seems unreasonable to me that the whole mechanism of overloading operators was introduced into the language only to provide a different naming convention for ordinary functions, while offering no real syntactical advantage when it comes to mathematical expressions.

But, of course, I hope I am wrong in assuming this.

Which brings me to ask: Does GCC have the ability to create automatic intermediates? If not, what compilers aside from the MS brands are capable of this?

Or have I gone about this in the wrong way altogether and there is a better technique for creating the same effect?

2

2 Answers

4
votes

Your non-modifying operators need to take their arguments by const reference, e.g.

template<typename T>
inline quaternion<T> operator+(const quaternion<T> &a, const quaternion<T> &b)
{return quaternion<T>(a.x+b.x,a.y+b.y,a.z+b.z,a.w+b.w);}

Standard C++ does not allow you to bind unnamed temporaries (which your intermediate values are) to non-const references. It sounds like MSVC++ might have permitted this as an extension.

3
votes

The code you've shown should not require rewriting for gcc or anything other properly functioning C++ compiler. C++ requires the compiler to be able to generate temporaries (what you're calling intermediates), including the ones you've shown. While there are some differences between what gcc will accept and what VC++ will accept, they're usually pretty minor (typically VC++ accepting code that it theoretically shouldn't). In the code above, you have exactly that: you're passing arguments by non-const reference, but temporaries are only supposed to be able to be passed by value, or const reference. Change that, and gcc should accept the code.

If you have other problems, my advice would be to ask another question more directly about some examples of code you're trying to port to gcc, and telling about what problems you're encountering in doing so.