Search code examples
c++oopfunction-pointersfriend

Function Pointer as a Friend Function


I am using function pointers within a class to allow extendable functionality at runtime.

I have typedef'd the function signature:

typedef f32 generate_height(f32 x, f32 y);

Now, within the class I am using function pointers:

class TerrainChunk
{
...
private:
        generate_height *heightgen;
...
}

I would like this function pointer to be allowed to access private attributes of TerrainChunk. I could pass them, but different functions might need different attributes - for example, I might need to access the Mesh of the terrain in some functions, or the location of the terrain in others. So this would quickly become a very large function signature, which is neither ideal nor extensible.

I tried putting the friend keyword in different places, which did not work.

Any suggestions on how I could achieve this functionality?


Solution

  • You can't make a function pointer a friend of TerrainChunk. You can only make functions a friend of TerrainChunk.

    That means you can only make a finite set of functions friends. You can't load an arbitrary function at run-time and have it able to read the private parts of TerrainChunk.

    As Some programmer dude suggests, the work-round is to pass a reference (or pointer) to (const) TerrainChunk to the function, and give TerrainChunk enough public accessor functions that the generate_height functions can obtain all the info they need.

    (You can make the accessors in-line, so this won't have any performance penalty).