Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot access private member declared in class error while instantiating template

Tags:

c++

templates

My code is as follows

template <typename T>

class name
{
public:
    name() : h_(0){}

    template <typename U>
    operator name<U>()
    {
        name<U> u;
        u.h_ = h_;
        return u;
    }
private:
    int h_;
};

int main(void)
{
    name<int> a;
    name<double> b = a;
    return 0;
}

The error that I get is int name<double>::h_ is private. How to fix the error?

like image 730
rahul garg Avatar asked Oct 04 '10 11:10

rahul garg


1 Answers

name<int> and name<double> are different instantiations, and thus are actually different classes. Their private members cannot be shared by default. You need to make name<T> friend to all other name's.

template <typename T>

class name
{
public:
    name() : h_(0){}

    template <typename U>
    operator name<U>()
    {
        name<U> u;
        u.h_ = h_;
        return u;
    }
private:
    int h_;
    template <typename>   // <--
    friend class name;   // <--
};

int main(void)
{
    name<int> a;
    name<double> b = a;
    return 0;
}
like image 177
kennytm Avatar answered Sep 20 '22 03:09

kennytm