【问题标题】:Accessing a private constructor of a template class in C++在 C++ 中访问模板类的私有构造函数
【发布时间】:2015-08-01 08:54:28
【问题描述】:

我在尝试访问指定为模板参数的派生类的私有构造函数时遇到了一些困难。我希望指定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() {}
};

创建尝试:

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

我得到的错误是:

错误 C2248“Derived::Derived”:无法访问在“Derived”类中声明的私有成员

请问有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: c++ templates friend


    【解决方案1】:

    您的 Creator 类不需要授予朋友访问其模板参数的权限。

    template <typename T>
    class Creator
    {
    public:
    
        static void Create()
        {
            instance = new T;
        }
    private:
        static T* instance;
        // friend T; NOT USEFUL
    };
    

    您需要提供来自具有私有成员的类的好友访问权限。

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

    这允许您的代码编译并获得您想要的行为。

    请注意,通过在您的模板类中声明friend T;,您实际上是在将您的私有成员暴露给您使用Creator 专门研究的任何T。因此,您可以让某人写...

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

    ...如果他们使用了您的 Creator 模板。

    【讨论】:

    • 天哪,我不敢相信我把朋友声明弄错了。谢谢你的回答
    猜你喜欢
    • 2011-05-08
    • 2016-12-30
    • 2021-04-17
    • 2011-02-05
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    相关资源
    最近更新 更多