【问题标题】:Templated Proxy design pattern模板化代理设计模式
【发布时间】:2018-02-04 13:13:22
【问题描述】:

我有一个简单且可重现的代码,如下所示:

template <typename T>
class Proxy {
private:
    Wrap<T> &self; // If I comment this, it will work
public:
    Proxy() {}
};

template <typename T>
class Wrap {
    T *p;
public:
    Proxy<T> foo() {
        return Proxy<T>();
    }
};

int main()
{
    return 0;
}

我得到的错误是:

'Wrap' 没有命名类型

如果我评论Wrap&lt;T&gt; &amp;self,那么它会起作用,但这不是我需要的。我需要Wrap&lt;T&gt; 成为Proxy 班级的成员。我怎样才能做到这一点?

【问题讨论】:

  • 在Proxy之前声明。
  • 然后我得到Proxy does not name a type。
  • 声明与定义不同。
  • 谢谢你,马里奥!我明白了!

标签: c++ templates declaration forward-declaration


【解决方案1】:

您可以在Proxy 的类定义之前添加Wrap 的forward declaration,否则编译器无法知道它是类模板的名称。值得注意的是,引用数据成员的类型并不要求为complete type,所以这里前向声明就足够了。

// forward declaration
template <typename T>
class Wrap;

template <typename T>
class Proxy {
private:
    Wrap<T> &self;
public:
    Proxy() {}
};

顺便说一句,以下问题是引用数据成员 self 未初始化。

LIVE of Clang

错误:“代理”的构造函数必须显式初始化引用成员“自我”

【讨论】:

    【解决方案2】:

    你需要添加一个前向声明:

    template<class T> class Wrap;
    
    template <typename T>
    class Proxy {
    private:
        Wrap<T> &self;
    public:
        Proxy() {}
    };
    
    template <typename T>
    class Wrap {
        T *p;
    public:
        Proxy<T> foo() {
            return Proxy<T>();
        }
    };
    
    int main()
    {
        return 0;
    }
    

    代码只是从 OP 的问题中复制而来。但是您仍然需要关注会员Wrap&lt;T&gt; &amp;self。作为参考,它应该在构造函数中初始化。

    【讨论】:

    • 谢谢您,先生!我不知道“前向声明”这样的概念。
    猜你喜欢
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2021-12-13
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多