I’m trying to make a custom collision engine for academic purposes and I got stuck on a general c++ programming issue. I already have all the geometries which work properly and the collision test also working properly.
The engine uses those 2 classes to create a queue of geometries to test :
class collidable;
template<typename geometry_type>
class collidable_object : public collidable;
Since multiple geometry types are possible, I didn't want to have to specify manually any collisions to be tested.
Instead I used this "technique" to implement the double-dispatching:
class collidable
{
public:
typedef bool (collidable::*collidable_hit_function)(const collidable& ) const;
virtual ~collidable() = 0 {}
virtual collidable_hit_function get_hit_function() const = 0;
};
template<typename geometry_type>
class collidable_object : public collidable
{
public:
explicit collidable_object( geometry_type& geometry ) :
m_geometry( geometry )
{}
~collidable_object(){}
virtual collidable_hit_function get_hit_function() const
{
return static_cast<collidable_hit_function>( &collidable_object<geometry_type>::hit_function<geometry_type> );
}
template<typename rhs_geometry_type>
bool hit_function( const collidable& rhs ) const
{
return check_object_collision<geometry_type, rhs_geometry_type>( *this, rhs );
}
const geometry_type& geometry() const
{
return m_geometry;
}
private:
geometry_type& m_geometry;
};
bool check_collision( const collidable& lhs, const collidable& rhs )
{
collidable::collidable_hit_function hit_func = lhs.get_hit_function();
return (lhs.*hit_func)( rhs );
}
where the function check_object_collision
is a template function which tests for collision and has been tested.
My question is as follows: the cast in the function get_hit_function
does compile but seems suspicious... am I doing something horribly wrong which will lead to undefined behavior and multiple nightmares or is it OK to cast template member function pointers from one derived class to another.
what confuses me is that in visual c++ 2012 this compiles and seems to work properly...
What could make this cast go horribly wrong?
I don't really understand what casting function pointers implies...
As a follow up question, would there be a way to implement this in a safe way