C++ Logo


Advanced search

[std-proposals] Impose friendship when needed

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sun, 17 Jul 2022 19:05:36 +0100
Recently I was working with an RS232 library when programming a
microcontroller in C++. I needed a little finer control over the library's
inner workings, more control than the library provided. I had to edit the
library's header file to change the visibility of one of the class's member
variables, I changed it from 'private' to 'public', and also I made one of
the member functions 'public'. Alternatively I could have added one line at
the end of the class definition:

    friend class MyOwnClass;

and then I could have accessed all the private members through static
member functions belonging to MyOwnClass.

I propose that we should be able to "impose friendship" without editing the
library's header files. For example:

    class Foo { int monkey; };

    int main(void)
        Foo obj;

        using friend Foo;

        obj.monkey = 5;

The statement "using friend Foo" only has an effect within 'main', similar
to how "using namespace std" would have limited scope here.

Alternatively, the syntax could be on an access-by-access basis, something
like as follows:

    int main(void)
        Foo obj;

        friend<obj>.monkey = 5;

or the syntax could be:

    friend<obj.monkey> = 5;

or maybe:

    std::friend(obj, monkey) = 5;


    friend >> obj.monkey = 5;

Some of you might be thinking: "Why affirm such subterfuge when the author
of the library obviously didn't want you messing around in there?", well
computer programming isn't an exact science. Indeed we have paradigms and
design patterns, but really at the end of the day we're trying to get
things done, and this might mean following the instructions from Step 1 to
Step 9 but then deviating at Step 10.

Being able to manually impose friendship when and where you need it, would
mean not needing to edit the 3rd party library's header file.

Received on 2022-07-17 18:01:03