template friend functions of template class

后端 未结 4 1476
庸人自扰
庸人自扰 2021-01-13 07:12

I have the following template class and template function which intends to access the class\' private data member:

#include 

template

        
4条回答
  •  长情又很酷
    2021-01-13 07:41

    Well there is a solution that is both simple and involving separation between declaration & definition of the friend function. In the declaration of the friend function (inside the class) you have to give a different template param from the one the class accepts (and it make sense cause this function is not a member of this class).

    template
    class MyVar
    {
        int x;
    
        template
        friend void printVar(const MyVar & var);
    
        template
        friend void scanVar(MyVar & var);
    };
    
    template
    void printVar(const MyVar & var) {
    
    }
    
    template
    void scanVar(MyVar & var) {
    
    }
    

    No forward declaration needed, as well as there is a separation of declaration & definition.

提交回复
热议问题