C++: Possibility of inline function, friend to multiple classes?

151 views Asked by At

I am working on implementing an intersection test between a sphere and a triangle.

I want to design a function to do this. The function sphere_triangle_intersection_test( ... ) should be declared as a friend function to both class sphere and class triangle, as this allows access to private members. (Thus likely to be more efficient, due to no function calls to get() or set() methods.

The function will be called quite a lot of times each loop, so it would be nice to make it an inline function.

However, inline functions, at least to my understanding, must appear (be defined) in the same file as the class declaration.

Since I am using a format of one-header-per-class, is there a way around this?

I guess one possibility would be:

  • Create a file sphere.hpp for the class sphere to reside in.
  • Create a file triangle.hpp for the class triangle to reside in.
  • Declare as friend inline [return type] the function performing the intersection test, in both classes.
  • Create a file collisiontest.impl containing the definition of the inline function to perform the test.
  • #include "sphere.hpp" in triangle.hpp.
  • At the end of triangle.hpp, `#include "collisiontest.impl".

Seems a bit dodgy though... it would be easy to forget that collisiontest.impl was included at the bottom of a file...

Does anyone have any suggestions about how I might change / improve what I've got here?

Edit

It just occurred to me I could create yet another file, shapes_INCLUDE_ME.hpp with the following content:

// shapes_INCLUDE_ME.hpp

#ifndef __shapes__include__me__hpp__
#define __shapes__include__me__hpp__ // not necessary, but good practice

    #include "sphere.hpp"
    #include "triangle.hpp"

    #include "collisiontest.impl"

#endif // __shapes__include__me__hpp__

Then you would include just the one file, might neaten things up a bit? Now there's no issue about forgetting the #include at the end of the class file.

0

There are 0 answers