template friend functions of template class

后端 未结 4 1432
庸人自扰
庸人自扰 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:37

    I managed to get the following work

    #include 
    
    template
    class MyVar;
    
    template
    void printVar(const MyVar& var);
    
    template
    void scanVar(MyVar& var);
    
    template
    class MyVar
    {
        int x;
        friend void printVar(const MyVar& var);
        friend void scanVar(MyVar& var);
    };
    
    template
    void printVar(const MyVar& var)
    {
        std::cout << var.x << std::endl;
    }
    
    template
    void scanVar(MyVar& var)
    {
        std::cin >> var.x;
    }
    
    struct Foo {};
    
    int main(void)
    {
        MyVar a;
        scanVar(a);
        printVar(a);
        return 0;
    }
    

    UPD: http://en.cppreference.com/w/cpp/language/friend talks about a similar case with operators under "Template friend operators":

    A common use case for template friends is declaration of a non-member operator overload that acts on a class template, e.g. operator<<(std::ostream&, const Foo&) for some user-defined Foo

    Such operator can be defined in the class body, which has the effect of generating a separate non-template operator<< for each T and makes that non-template operator<< a friend of its Foo

    ...

    or the function template has to be declared as a template before the class body, in which case the friend declaration within Foo can refer to the full specialization of operator<< for its T

提交回复
热议问题