Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

c++ - Templated Proxy design pattern

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;
}

The error I get is:

'Wrap' does not name a type

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() {}
};

BTW the following issue would be that the reference data member self is not initialized.

LIVE of Clang

error: constructor for 'Proxy' must explicitly initialize the reference member 'self'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...