C++ – Member and Function Injection Across Multiple Classes

aspect-orientedcc++11

I have a problem in which a variety of classes in C++ will want some functionality that is neither a "has a" nor an "is a" relationship.
The problem is that there are some members with associated functions having to do with handling player pointers that some menus and in game objects will need to have.
I could copy the functionality across all of them, but I'd rather inject the functionality as advice, so that the functionality is shared.
The classes that need the functionality do not share a super in the class tree.

Normally I might use something akin to aspect orientation, making an Aspect that has all the desired functionality and adding it to all of the classes as advice, but because of the C++ codebase at the company I cannot do this.

Is there a good "plain C++" solution to this that I'm overlooking? (c++11 allowed)
Right now I hope to use interfaces to do something similar.

edit:
i'll be experimenting with each solution, perhaps asking further questions, and will figure out the best solution within the next few days.
want to give this thorough consideration for future use.

Best Answer

Is all the functionality known at compile time? If so, template metaprogramming might work. See a real example here, but something like this ---

template<class T> ExtraFunctionality {
  //do something with instances of class T
}

template<class T> OtherExtraFunctionality {
  //do something else with instances of class T
}

template< template<class> class Extras = ExtraFunctionality >
class Menu: public AbstractMenu, Extras<Menu> {
  typedef Extras<Menu> Ext;  //for convenience - not required
  //do something with what you inherited from Extras.
}

template< template<class> class Extras = ExtraFunctionality >
class GameObject: public AbstractGameObject, Extras<GameObject> {
  //same deal
}

now you can instantiate

Menu<> menu;

for the Menu with ExtraFunctionality or

Menu<OtherExtraFunctionality>

if you want something different.

This is an example of CRTP mentioned by @Deduplicator.

Related Topic