Sam Hertz
Sam Hertz

Reputation: 161

Cyclic Template

Suppose template class A is defined as follows:

template <typename T>
class A
{
    B<T> b;
};

Suppose template class B is defined as follows:

template <typename T>
class B
{
    A<T> a;
};

Ideally, these classes would be defined in separate headers with inlined implementations. However, this would cause a cyclic inclusion problem. One solution is to put the implementation of the templated classes into a cpp file. However, this would require specialized template instantiations.

Is there a way to keep the implementation of the classes inlined and avoid a cyclic inclusion dependency? I would like to avoid using pointers if it is possible.

Thanks,

Sam

Upvotes: 3

Views: 130

Answers (1)

log0
log0

Reputation: 10937

Forward declare your classes and use header guards (or non-standard #pragma once). http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.11

Note that two classes cannot fully contains an object of each other. This would describe an object of infinite size...
http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.12

Upvotes: 4

Related Questions