简体   繁体   中英

Accessing a private constructor of a template class in C++

I'm having some difficulties attempting to access a private constructor of a derived class, which is specified as a template parameter. I was hoping that specifying friend T would solve the issue, but unfortunately it has no effect.

template <typename T>
class Creator
{
public:

    static void Create()
    {
        instance = new T;
    }
private:
    static T* instance;
    friend T;
};

template <typename T>
T* Creator<T>::instance(nullptr);

class Test
{
private:
    Test() {}
};

Creation attempt:

int main()
{
     Creator<Test>::Create();
}

The error I get is:

Error C2248 'Derived::Derived': cannot access private member declared in class 'Derived'

Any ideas how I could resovle this please?

Your Creator class doesn't need to give friend access to its template parameter.

template <typename T>
class Creator
{
public:

    static void Create()
    {
        instance = new T;
    }
private:
    static T* instance;
    // friend T; NOT USEFUL
};

You need to provide friend access from the class that has the private member.

class Test
{
    friend Creator<Test>; // provide friend access to Creator<Test> specialization
private:
    Test()
    {
    }
};

This allows your code to compile and get the behaviour you want.

As a note, by declaring friend T; in your template class, you are actually exposing your private members to any T that you specialize into with Creator. You could therefore have someone write...

class Test
{
private:
    Test()
    {
        // you don't really want this, do you?
        delete Creator<Test>::instance;
    }
};

...if they used your Creator template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM