template friend functions of template class

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

    The simplest option is to define the friend within the class:

    template
    class MyVar
    {
        int x;
    
        friend void printVar(const MyVar & var) {
            std::cout << var.x << std::endl;
        }
        friend void scanVar(MyVar & var) {
            std::cin >> var.x;
        }
    };
    

    The downside is that the functions can only be called through argument-dependent lookup. That's not a problem in your example, but might be a problem if they don't have a suitable argument, or you want to specify the name without calling it.

    If you want a separate definition, then the template will have to be declared before the class definition (so it's available for a friend declaration), but defined afterwards (so it can access the class members). The class will also have to be declared before the function. This is a bit messy, so I'll only show one of the two functions:

    template  class MyVar;
    template  void printVar(const MyVar & var);
    
    template
    class MyVar
    {
        int x;
    
        friend void printVar(const MyVar & var);
    };
    
    template  void printVar(const MyVar & var) {
        std::cout << var.x << std::endl;
    }
    

提交回复
热议问题