What is the point of the complicated scoping rules for friend declarations?

前端 未结 1 1038
伪装坚强ぢ
伪装坚强ぢ 2021-02-20 05:25

I recently discovered that friend declarations scoping follows extremely peculiar rules - if you have a friend declaration (definition) for a function or a class th

相关标签:
1条回答
  • 2021-02-20 06:08

    Well, for answering that, you have to look at another major feature of C++: Templates.

    Consider a template such as this:

    template <class T>
    struct magic {
        friend bool do_magic(T*) { return true; }
    };
    

    Used in code like this:

    bool do_magic(void*) { return false; }
    
    int main() {
        return do_magic((int*)0);
    }
    

    Will the exit-code be 0 or 1?

    Well, it depends on whether magic was ever instantiated with int anywhere observable.
    At least it would, if friend-functions only declared inline would be found by ordinary lookup-rules.
    And you can't break that conundrum by just injecting everything possible, as templates can be specialized.

    That was the case for a time, but was outlawed as "too magic", and "too ill-defined".

    There were additional problems with name injection, as it wasn't nearly as well-defined as hoped for. See N0777: An Alternative to Name Injection from Templates for more.

    0 讨论(0)
提交回复
热议问题