gpt4 book ai didi

c++ - 嵌套在其他任何类别中的已知类名称的C++模板 friend 声明

转载 作者:行者123 更新时间:2023-12-01 14:29:05 25 4
gpt4 key购买 nike

晚上好。
我在编写一些通用代码(至少在C++ 11中)时遇到以下问题:
考虑一个名为I的类,它可以嵌套在各种类A,B,...,N中:

class A
{
protected:
friend class I;
class I
{
} i;
};

class B
{
protected:
friend class I;
class I
{
} i;
};

etc.
实际上 I是一种界面工具,可以自动插入各种用户类A ... N中。不在乎这样做的理由...
然后有一个特定的类Z,目标是将任何 I声明为Z的 friend ,以便任何 I以及其他任何东西都不能使用Z,无论A ... N(稍后定义)类如何嵌套在 I中。
如果我这样声明:
class Z
{
friend class A; // <--- but I don't want to have to know this one
friend class I;
private: // creation and use of Z are restricted to tools like I
Z();
// other methods
};
然后它仅适用于 A::I:
通过 A::I::some_function()可以构建和使用Z,
但不是 B::I或B ... N中的其他任何源。
如果没有 friend class A;,则 I都无法访问Z。
  • 如何使其通用?

  • 我正在寻找一种写模板 friend 声明的方法,该声明可以授予对任何 X::I的访问权限,其中X是模板参数。
    当然不是 I的模板参数,因为 I不是模板。
    当然,我不想授予对任何类X的访问权限,以便任何 X::I也可以访问Z!
    以下内容不起作用:
    class Z
    {
    template< class X> friend class X::I;
    ...
    };
    =>错误:“我”不是“X”的成员
    从gcc版本5.4.0 20160609(Ubuntu 5.4.0-6ubuntu1〜16.04.11)
    有正确语法的想法吗?我没有在引用文献中找到该用例...
    非常感谢,
    亲切的问候。
    =================在8月16日添加:精度: I持久地作为 A(或其他)的一部分存在,而 Z是仅在 I的特定操作期间存在的工具,可以重复此操作,然后创建新的 Z,使用该代码,然后每次将其删除 I方法。
    另外 Z具有相应的有效负载,我不想让它成为嵌入 I的每个对象的永久部分。例如,通过使 Z继承 I

    最佳答案

    您可以通过使I继承Z,并使Z成为抽象基类(因此不能直接访问)来实现您要尝试的操作。
    类似于:

    class Z
    {
    virtual void __() = 0;
    public:
    virtual ~Z() = default;
    void method() { std::cout << "Method from Z" << std::endl; }
    };

    class A
    {
    friend class I;

    public:
    class I : public Z
    {
    void __() final {}
    public:
    static Z *make_z();
    } i;
    };

    Z *A::I::make_z()
    {
    return new I();
    }

    int main()
    {
    Z *z = A::I::make_z();
    z->method();

    return 0;
    }

    关于c++ - 嵌套在其他任何类别中的已知类名称的C++模板 friend 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63417735/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com