Friends access to an arbitrary class?
Bill Baxter
dnewsgroup at billbaxter.com
Sun Jul 8 20:39:13 PDT 2007
Ald wrote:
> Suppose I have a hierarchy of classes, with base class Human.
> Each Human has a reference to a class of (super) type Algorithm, which contains the implementation of the Human's behavior.
>
> How can I give every Algorithm (and derivative) access to every private method and member to any Human (or derivative) that holds reference to that Algorithm?
>
> I tried inheriting from nested classes and from classes in the same module.
Being in the same module (i.e. same file) should work. If FunkyHuman
and CoolAlgorithm are in the same module CoolAlgorithm can access
anything in FunkyHuman. Are you saying you tried that and it didn't work?
Anyway, you might be barking up the wrong tree. Having a member that
knows how to manipulate every private attribute of it's owner sounds to
me more like a use case for a mixin. I.e. reuse Algorithms by making
them an actual part of the classes you want them to act on.
template CoolAlgorithm()
{
void act_cool() {
mode = COOL;
}
}
class FunkyHuman
{
mixin CoolAlgorithm; // FunkyHuman now has an act_cool() method
private:
int mode = UNCOOL;
}
You might even be able to make the mixin an alias template parameter so
you can create FunkyHumans with different algorithms (don't recall if
that works actually...)
class FunkyHuman(alias AlgoMixin)
{
mixin AlgoMixin;
...
}
If you need to unplug and replace Algorithms at runtime, then it seems
like you need to reconsider whether the parts of Human they need access
to are really private. If external objects need to access it, then it
sounds more like it's part of the public interface.
--bb
More information about the Digitalmars-d-learn
mailing list