• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C++ syntax help: Friend template class of a template class using the same type

slugg

Diamond Member
Hello there. I'm trying to make two template classes, where one is the friend of the other, but they use the same class. For example:

Code:
template <class T>
class SluggFactory {
[INDENT]public: //functions here[/INDENT]
}

template <class T>
class SluggObject {
[INDENT]//members and other private stuff here
public:
friend class SluggFactory<T>;[/INDENT]
}

I want SluggFactory to be able to access SluggObject's private members and functions. This is trivial without templates (literally exactly what I have already, except take out the template stuff). A nested private class wouldn't work for me because the user needs to be able to directly use SluggObject objects.

I've googled around and the best I can really find is friend template functions to template classes. I'm talking about making the entire template class a friend of the other template class using the same type.

How to do? Thanks in advance 🙂

Edit: I've been a victim of sloppy typing/typos. For anyone else in Google-land looking for a solution to this problem, here it is:

Code:
[B]//You'll need a forward declaration of the friend class here, like so:
template <class T> SluggFactory<T>;[/B]

[B]//Now define the base class first:[/B]
template <class T>
class SluggObject {
[INDENT]//members and other private stuff here
public:
[B]template <class T> friend class SluggFactory;[/B][/INDENT]
}

[B]//Then define the friend class:[/B]
template <class T>
class SluggFactory {
[INDENT]public: //functions here[/INDENT]
}
 
Last edited:
Forward declarations, and the need for them, become a lot clearer if you think like the compiler. It merges the source file and any includes and then processes them from the top down, and it doesn't know about any type it hasn't encountered while processing the source. Modern managed languages with type metadata lull us into thinking that the compiler knows everything in the solution, all the time.
 
Yeah. What was mainly giving me an issue was the actual "friend class" line. I'm not at a point where I can compile at the moment, so I was relying on intellisense to tell me if it was okay. All good now.

I can't wait until I'm done with this thing. I'm making an entire image processing library from scratch. I just can't stand OpenCV... it's slow, hard to use, and clunky. Mine will be better 😉
 
Back
Top