I'm attempting to write a policy-based host class (i.e., a class that inherits from its template class), with a twist, where the policy class is also templated by the host class, so that it can access its types. One example where this might be useful is where a policy (used like a mixin, really), augments the host class with a polymorphic clone() method. Here's a minimal example of what I'm trying to do:
template <template <class> class P>
struct Host : public P<Host<P> > {
typedef P<Host<P> > Base;
typedef Host* HostPtr;
Host(const Base& p) : Base(p) {}
};
template <class H>
struct Policy {
typedef typename H::HostPtr Hptr;
Hptr clone() const {
return Hptr(new H((Hptr)this));
}
};
Policy<Host<Policy> > p;
Host<Policy> h(p);
int main() {
return 0;
}
This, unfortunately, fails to compile, in what seems to me like circular type dependency:
try.cpp: In instantiation of ‘Host<Policy>’:
try.cpp:10: instantiated from ‘Policy<Host<Policy> >’
try.cpp:16: instantiated from here
try.cpp:2: error: invalid use of incomplete type ‘struct Policy<Host<Policy> >’
try.cpp:9: error: declaration of ‘struct Policy<Host<Policy> >’
try.cpp: In constructor ‘Host<P>::Host(const P<Host<P> >&) [with P = Policy]’:
try.cpp:17: instantiated from here
try.cpp:5: error: type ‘Policy<Host<Policy> >’ is not a direct base of ‘Host<Policy>’
If anyone can spot an obvious mistake, or has successfuly mixing CRTP in policies, I would appreciate any help.