• Advertisement
Sign in to follow this  

Why does this happen? (const and/or template problem)

This topic is 4586 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I currently have a template class for a 3-d vector, lifted pretty much from the WildMagic engine. An abridged version looks like this:
	template<class Real>
	class Vec3 {
	public:		
		/* element access */
		Real x() const;
		Real& x();
		Real y() const;
		Real& y();
		Real z() const;
		Real& z();

		/* arithmetic operations */
		Vec3 operator+ ( const Vec3& v ) const;
		Vec3 operator- ( const Vec3& v ) const;
		Vec3 operator* ( Real a );
		Vec3 operator/ ( Real a );
		Vec3 operator- ();

		/* constructors */
		Vec3( Real x = 0, Real y = 0, Real z = 0 );
		Vec3( const Vec3& v );
	private:
		Real m_tuple[3];
	};

	typedef Vec3<float> Vec3f;
	typedef Vec3<double> Vec3d;

The relevant operator definitions:
template <class Real>
	Vec3<Real> Vec3<Real>::operator+ ( const Vec3& v ) const {
		return Vec3( m_tuple[0] + v.m_tuple[0],
			m_tuple[1] + v.m_tuple[1],
			m_tuple[2] + v.m_tuple[2] );
	};

template <class Real>
	Vec3<Real> Vec3<Real>::operator* ( Real a ) {
		return Vec3( m_tuple[0] * a,
			m_tuple[1] * a,
			m_tuple[2] * a );
	};

I then have a template class for a line:
template<class Real>
	class Line3 {
	public:
		/* member access */
		Vec3<Real> Origin() const;
		Vec3<Real>& Origin();
		Vec3<Real> Direction() const;
		Vec3<Real>& Direction();

		/* line operations */
		Vec3<Real> Point( Real t ) const;

		/* constructors */
		Line3();
		Line3( const Vec3<Real>& origin, const Vec3<Real> direction );
		Line3( const Line3& line3 );
	private:
		Vec3<Real> m_Origin,
			m_Direction;
	};

	typedef Line3<float> Line3f;
	typedef Line3<double> Line3d;

And the Point function, which should return a point on the line t units along it, looks like this:
template<class Real>
		Vec3<Real> Line3<Real>::Point( Real t ) const {
			return Origin() + Direction() * t;
		};
And it works fine. However, I originally implemented it like this:
template<class Real>
		Vec3<Real> Line3<Real>::Point( Real t ) const {
			return m_Origin + m_Direction * t;
		};
And this didn't work. It only returned the value of m_Origin. I don't really understand why this was the case. Is this due to me mixing up const's?

Share this post


Link to post
Share on other sites
Advertisement
From a quick glance the problem might be that your scalar multiplication function in the Vec3<> class lacks the const keyword. Also your scalar division and unary minus functions too.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement