简体   繁体   English

在C ++中访问模板类的私有构造函数

[英]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. 我希望指定friend T可以解决此问题,但不幸的是,它没有任何作用。

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' 错误C2248:“派生::派生”:无法访问在“派生”类中声明的私有成员

Any ideas how I could resovle this please? 有什么想法可以解决这个问题吗?

Your Creator class doesn't need to give friend access to its template parameter. 您的Creator类无需授予朋友访问其模板参数的权限。

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; 注意,声明friend T; in your template class, you are actually exposing your private members to any T that you specialize into with Creator. 在您的模板类中,您实际上是在将私有成员暴露于您通过Creator专门研究的T中。 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. ...如果他们使用了您的创作者模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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