问题描述
我有一个简单且可复制的代码,如下所示:
I have a simple and reproducible code, which looks like so:
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;
}
我得到的错误是:
如果我评论包装< T> & self
,那么它将起作用,但这不是我所需要的。我需要 Wrap< T>
成为 Proxy
类的成员。我该如何实现?
If I comment Wrap<T> &self
, then it will work, but this is not what I need. I need Wrap<T>
to be a member of Proxy
class. How can I achieve this?
推荐答案
您可以添加(在 Proxy
,否则编译器无法知道它是类模板的名称。值得注意的是,引用数据成员不需要类型为,因此在这里前向声明就足够了。
You could add forward declaration of Wrap
before the class definition of Proxy
, otherwise the compiler can't know that it's the name of a class template. It's worth noting that reference data member doesn't require the type to be complete type, so forward declaration is enough here.
// forward declaration
template <typename T>
class Wrap;
template <typename T>
class Proxy {
private:
Wrap<T> &self;
public:
Proxy() {}
};
顺便说一句,下面的问题是引用数据成员 self
未初始化。
BTW the following issue would be that the reference data member self
is not initialized.
这篇关于模板化代理设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!