Reputation: 505
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?
Upvotes: 2
Views: 1693
Reputation: 3239
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.
Upvotes: 5