When should you use 'friend' in C++?

前端 未结 30 2187
孤街浪徒
孤街浪徒 2020-11-22 10:12

I have been reading through the C++ FAQ and was curious about the friend declaration. I personally have never used it, however I am interested in exploring the language.

30条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 10:54

    I'm only using the friend-keyword to unittest protected functions. Some will say that you shouldn't test protected functionality. I, however, find this very useful tool when adding new functionality.

    However, I don't use the keyword in directly in the class declarations, instead I use a nifty template-hack to achive this:

    template
    class FriendIdentity {
    public:
      typedef T me;
    };
    
    /**
     * A class to get access to protected stuff in unittests. Don't use
     * directly, use friendMe() instead.
     */
    template
    class Friender: public ParentClass
    {
    public:
      Friender() {}
      virtual ~Friender() {}
    private:
    // MSVC != GCC
    #ifdef _MSC_VER
      friend ToFriend;
    #else
      friend class FriendIdentity::me;
    #endif
    };
    
    /**
     * Gives access to protected variables/functions in unittests.
     * Usage: friendMe(this, someprotectedobject).someProtectedMethod();
     */
    template
    Friender & 
    friendMe(Tester * me, ParentClass & instance)
    {
        return (Friender &)(instance);
    }
    

    This enables me to do the following:

    friendMe(this, someClassInstance).someProtectedFunction();
    

    Works on GCC and MSVC atleast.

提交回复
热议问题