Implicit conversion

OPEN

I have a Position_Component and Velocity_Component that both contain a vec3f.

I want to be able to use operators on these components and similar components i will make in the future as if they are vec3f, so i've defined an implicit conversion to a vec3f for both of these types of components. When i do try to use operators on them as if they are vec3f, i get errors that the operators are not defined.

struct Position_Component : public Component<Position_Component>
{
	math::vec3f position;
	Position_Component() : position(math::vec3f{ 0.0, 0.0, 0.0 }) {}
	Position_Component(const math::vec3f& position) : position(position) {}

	operator math::vec3f() { return position; };
};

struct Velocity_Component : public Component<Velocity_Component>
{
	math::vec3f velocity;
	Velocity_Component() : velocity(math::vec3f{ 0.0, 0.0, 0.0 }) {}
	Velocity_Component(const math::vec3f& velocity) : velocity(velocity) {}

	operator math::vec3f() { return velocity; };
};

I dont get any errors if i explicitly cast the components to vec3f before adding them.

​

Edit: I release i want the implicit conversion to return a reference, but this is not why im getting an error.

More code in comments.

Posted Jul 26, 2019, 1:29 PM UTC · edited

114
Wh00ster•

What do you mean adding them? That sounds important. What’s the function you’re trying them in?

2
NazozOP•

With p being a position component and v being a velocity component, im trying to do this:

p += v * (float)dt;

instead of this

p.position += v.velocity * (float)dt;

or

(math::vec3f)p += (math::vec3f)v * (float)dt;

The full function is

void updateEntity(const double& dt, UnitGroup& units) override
{
	Velocity_Component& v = units.get<Velocity_Component>().first[0];
	Position_Component& p = units.get<Position_Component>().first[0];

	if (p.position.x < -boundary)
	{
		v.velocity.x *= -1.0f;
		p.position.x += -boundary - p.position.x;
	}
	else if (p.position.x > boundary) {
		v.velocity.x *= -1.0f;
		p.position.x -= p.position.x - boundary;
	}

	if (p.position.y < -boundary)
	{
		v.velocity.y *= -1.0f;
		p.position.y += -boundary - p.position.y;
	}
	else if (p.position.y > boundary) {
		v.velocity.y *= -1.0f;
		p.position.y -= p.position.y - boundary;
	}

	p += v * (float)dt;
}
1
Wh00ster•

Okay and where are the definitions to add/multiply/assign? Are they functions that can be found during ADL and overload resolution?

1
NazozOP•

Here is my vec3f struct:

#pragma once
#include <math.h>
//#include "vec3d.h"

namespace abyssengine {
	namespace math {
		struct vec3f
		{
			union {
				float elements[3];
				struct {
					float x, y, z;
				};
			};

			vec3f() : x(0.0f), y(0.0f), z(0.0f) {};
			vec3f(const float& scalar) : x(scalar), y(scalar), z(scalar) {};
			vec3f(const vec3f& vec) : x(vec.x), y(vec.y), z(vec.z) {};
			vec3f(const float& x, const float& y, const float& z) : x(x), y(y), z(z) {};

			//operator vec3d() { return vec3d{ static_cast<double>(x), static_cast<double>(y), static_cast<double>(z) }; }

			vec3f& add(const vec3f& other)
			{
				this->x += other.x; this->y += other.y; this->z += other.z;
				return *this;
			}

			vec3f& subtract(const vec3f& other)
			{
				this->x -= other.x; this->y -= other.y; this->z -= other.z;
				return *this;
			}

			vec3f& multiply(const vec3f& other)
			{
				this->x *= other.x; this->y *= other.y; this->z *= other.z;
				return *this;
			}

			vec3f& divide(const vec3f& other)
			{
				this->x /= other.x; this->y /= other.y; this->z /= other.z;
				return *this;
			}

			vec3f& add(const float& scalar)
			{
				this->x += scalar; this->y += scalar; this->z += scalar;
				return *this;
			}

			vec3f& subtract(const float& scalar)
			{
				this->x -= scalar; this->y -= scalar; this->z -= scalar;
				return *this;
			}

			vec3f& multiply(const float& scalar)
			{
				this->x *= scalar; this->y *= scalar; this->z *= scalar;
				return *this;
			}

			vec3f& divide(const float& scalar)
			{
				this->x /= scalar; this->y /= scalar; this->z /= scalar;
				return *this;
			}


			// x ¤= y
			vec3f& operator+=(const vec3f& other) { return add(other); }
			vec3f& operator-=(const vec3f& other) { return subtract(other); }
			vec3f& operator*=(const vec3f& other) { return multiply(other); }
			vec3f& operator/=(const vec3f& other) { return divide(other); }

			vec3f& operator+=(const float& scalar) { return add(scalar); }
			vec3f& operator-=(const float& scalar) { return subtract(scalar); }
			vec3f& operator*=(const float& scalar) { return multiply(scalar); }
			vec3f& operator/=(const float& scalar) { return divide(scalar); }

			// x ¤ y
			vec3f operator+(const vec3f& other) const { return vec3f(*this).add(other); }
			vec3f operator-(const vec3f& other) const { return vec3f(*this).subtract(other); }
			vec3f operator*(const vec3f& other) const { return vec3f(*this).multiply(other); }
			vec3f operator/(const vec3f& other) const { return vec3f(*this).divide(other); }

			vec3f operator+(const float& scalar) const { return vec3f(*this).add(scalar); }
			vec3f operator-(const float& scalar) const { return vec3f(*this).subtract(scalar); }
			vec3f operator*(const float& scalar) const { return vec3f(*this).multiply(scalar); }
			vec3f operator/(const float& scalar) const { return vec3f(*this).divide(scalar); }

			//friend vec3f operator*(const vec3f& vec, const float& scalar) { return vec3f(vec).multiply(scalar); }


			float magnitude() const { return sqrt(x*x + y * y + z * z); }
			float dot(const vec3f& other) const { return this->x * other.x + this->y * other.y + this->z * other.z; };
			vec3f cross(const vec3f& other) const { return vec3f{ this->y * other.z - this->z * other.y, this->z * other.x - this->x * other.z, this->x * other.y - this->y * other.x }; }
			vec3f normalize() const { return *this / magnitude(); }
		};
	}
}
1
gcross•

You shouldn't both have separate classes for positions and velocities and also have there be implicit conversions between them. Either pick the former--which has the advantage of encoding information about the units into the type system so that the compiler will let you know if you accidentally are using the wrong unit in a particular place--or get rid of the distinction entirely and just use vec3f so that you don't have to worry about converting between these types; what you are saying you want to do now is to go to all the trouble of distinguishing these two different units only to immediately throw all of that information away by allowing implicit conversions.

If you want to write p += v * dt, you could accomplish this by defining a time class and defining * so that it operates on a velocity and a time to produce a position; because time is scalar quantity, you could then create an implicit constructor that converts floats to it.

2
NazozOP•

Their type is significant in other parts of the code, position and velocity components are part of a bigger picture; an ECS (Entity component system).

​

I dont understand what you mean by a time class. You mean something like advanceTime(position, velocity), and this function basically adds the velocity to the position without having to type out dt? Seems unnecessary.

1
gcross•

No, I mean that time could be a class instead of a float, and then the multiplication operator would take an instance of the velocity class and an instance of the time class and produce an instance of the position class, which could then be directly added to the other instance of the position class. That way you get to have your nice expression without implicit casts so that you don't give up type safety.

Having said that, if there is a lot more going on that you haven't told us that is significant, then it is hard to say anything useful.

2
NazozOP•

Oh! That makes alot of sense! I always thought of these kind of data containers as just their really basic type.

Thanks alot!

I guess instead of passing color as vec4's i should pass them as a color object, so that it doesent makes sense to add a position and a color for example, only colors to colors. Or maybe angles and lengths can be their own object?

Do you know if this kind of creating structs could noticeable affect performance? I cant imagine it would?

1
gcross•

I guess instead of passing color as vec4's i should pass them as a color object, so that it doesent makes sense to add a position and a color for example, only colors to colors. Or maybe angles and lengths can be their own object?

Yes, I personally am a big fan of that approach because putting all of this information into the types makes it harder for you to make mistakes without the compiler catching them. In fact, sometimes I will even create data types that do nothing more than wrap, say, an integer just because I have functions that take in multiple integers and I want to make sure that I can't pass them in the wrong order by accident. In a perfect world you would be confident that merely getting your code to compile would be sufficient to know that your code works.

Having said that, I am a bit more obsessive about such things then many in the C++ world probably are (due in part to having been contaminated by spending so much time writing code in Haskell :-) ), so please take my advice as being my particular perspective on this matter rather than the gospel truth, and strike your own balance. :-)

Do you know if this kind of creating structs could noticeable affect performance? I cant imagine it would?

I am not a compiler expert, but here are what I believe the considerations are.

First, if all you are doing is defining new structs/classes that only hold data members, then there should be no penalty at all because after the code is generated there is no need to reference their definitions anymore.

Now, once you start writing methods, you are causing more code to be generated, and this could be a problem because in the worst case scenario (which is very unlikely), all of those additional methods will be competing for room in the cache, and so there will be a lot of thrashing as a result which will result in a performance hit.

Having said that, if the methods you are defining are sufficiently small--which is very likely when you are creating lightweight wrapper classes--and are defined in the .h file rather than the .cc file, so all of the other files can see it, then when optimizations are turned on then the compiler will very likely choose to inline them, which means that it will copy the code in the method and paste it at the site of the method call. This might not seem like much of a gain because code is being copied, but in the process of inlining the compiler strips out the overhead of making a function call and also perform other optimizations that can make the code even smaller. (In theory LTO--link-time optimization--might make it so that you don't have to put the code in the header anymore, but I don't know.) Because of this, the method won't actually be called, and there will be no need to load it into the cache.

So in conclusion, if each of these structs is defining a large method, then this could cause problems. However, if you're classes are basically just lightweight wrappers over other types then you probably will only have fairly small methods that are going to get inlined, and if they aren't inlined then they won't take up too much space in the cache anyway. (Also, you might be able to use the inline keyword with a method that is not being inlined to strongly hint to the compiler that you want it to be inlined.) So basically, although there are theoretical concerns, in practice I doubt that there is much of a performance hit if any in created these struts/classes. But again, all of this information comes with the caveat that I am not a compiler expert. :-)

2
gcross•

Here, to be more explicit, something like the following:

struct Time
{
    float dt;

    Time(float dt_) : dt(dt_) {}
};

struct Velocity_Component : public Component<Velocity_Component>
{
    ...
    Position_Component operator*(Time t) const {
        return Position_Component(math::vec3f{ velocity.x*t.dt, velocity.y*t.dt, velocity.z*t.dt });
    }
};

I believe that the constructor makes floats implicitly convertible to Time, but if I am wrong adding Time(dt) isn't too much extra to type.

Now your expression p += v * dt should work just fine because the multiplication operator does the casting for you, but in a type-safe way.

2
manni66•

Error message: copy&pate! Code!

1
NazozOP•

My mistake. Posted code in other comment.

1
umlcat•

I know, my answer may sound weird, but maybe you should avoid implicit conversions, and show the operator or expression used to change one thing into another.

Implicit conversions are good for simple things like integer to float, or single char to string, but, objects and struct s are more complicated.

1