Jump to content
  • Advertisement
Sign in to follow this  
DaedalusOwnsYou

C++ Template Classes Referencing Each Other

This topic is 3747 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Say I have 2 classes that use templates:
template <class T>
class A {
   T value;

   A(T t) {
       value = t;
   }
}

template <class T>
class B {
   T value;

   B(T t) {
       value = t;
   }
}
Now suppose that those classes must each be able to use each other in some way, such as in constructors.
A(const B<T>& b) {
    whatever...
}

B(const A<T>& a) {
    whatever...
}
How can this be accomplished? Is there any way to to allow these classes to coexist in this fashion. Right now both classes exist in separate headers; is that the best way to do this kind of thing?

Share this post


Link to post
Share on other sites
Advertisement
template <class T>
class B; // Forward declaration

template <class T>
class A {
A(B<T> const &) {
}
};

template <class T>
class B {
B(A<T> const &) {
}
};



Share this post


Link to post
Share on other sites
It seems that you can do something like that:


template <class T>
class B;

template <class T>
struct A {
T value;

A(T t): value(t) {

}
A(B<T>& t);
};

template <class T>
struct B {
T value;

B( T t): value(t) { }
B( A<T> t): value(t.value) {}
};

template <class T>
A<T>::A(B<T>& t): value(t.value) {}



However, then A and B would have to be in the same header as you can't separate the declaration of templates from the implementation, and one constructor needs to go after the definition of the other class.

By the way, why do you want to do this? What do A and B really stand for?

Share this post


Link to post
Share on other sites
Thanks for the replies. I wasn't sure of the exact syntax of the forward declarations.

The actual use of this is that I want Matrix and Quaternion classes that can be used with each other. Something like


Matrix<float> m;
m.setIdentity();
m.rotate(stuff)
Quaternion<float> q = m.getRotation();

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!