Search code examples
c++templatesfriend

Using Template in friend class


First of all, my teacher asked mу to do something like that.

I have a class of two-dimensional array:

    #pragma once
    #include <iostream>
    #include "MyMaskedMassiv.h"

    template<typename T>
    class MyMaskedMassiv;

    template <typename T>
    class My2dMassiv{
    private:
        T* mas;
        int col;
        int str;
    public:
    ........
        friend class MyMaskedMassiv<T>;

        MyMaskedMassiv<T>& operator()(My2dMassiv<bool>& mask){
            MyMaskedMassiv<T> *maskMas = new MyMaskedMassiv<T>();
            maskMas->masiv = this;
            maskMas->mask = &mask; 
            return *maskMas;
        }
    }

And as you can see another class "MyMaskedMassiv" that have links to the first one:

    #pragma once
    #include "My2dMassiv.h"

    template <typename U>
    class My2dMassiv;

    template <typename T>
    class MyMaskedMassiv{
    private:
        My2dMassiv<T> *masiv;
        My2dMassiv<bool> *mask;
    public:
        friend class My2dMassiv<T>;
        friend class My2dMassiv<bool>;

        MyMaskedMassiv(){
            masiv = nullptr;
            mask = nullptr;
        }

        MyMaskedMassiv& operator=(const T& el){
            int s = masiv->str;
            int c = masiv->col;

            for(int i=0; i<c; i++)
                for( int j=0; j<s; j++)
                    if( this->mask->mas[i*s + j] == true)
                        this->masiv->mas[i*s + j] = el;  

        return *this;
        }
    }

So then I try to build I got an error:

    My2dMassiv.h:11:8: error: ‘bool* My2dMassiv<bool>::mas’ is private

    ../src/myproject/MyMaskedMassiv.h:27:36: error: within this context
             if( this->mask->mas[i*s + j] == true)

So.. what am I doing wrong?

If you want to see full code, check here: GIT


Solution

  • With

    template <typename T>
    class My2dMassiv{
        friend class MyMaskedMassiv<T>;
        // ...
    };
    

    Friendship is done only for matching T, I mean MyMaskedMassiv<int> can use private members of My2dMassiv<int> but not those from My2dMassiv<char>.

    You want

    template <typename T>
    class My2dMassiv{
        template <typename U>
        friend class MyMaskedMassiv;
        // ...
    };