I'd like to add a small increment over https://stackoverflow.com/a/5780976/1525238 that helped me better solve my peculiar use case, namely where the "main" class is a template and the "helper/inner" class also has to be a template1.
I used a nested namespace called detail
, made all "helper" content private and made the "main" class a friend
of the "helper" class:
template<__MAIN_TEMPLATE_PARAMS__> class Main;
namespace detail {
template<__HELPER_TEMPLATE_PARAMS__> class Helper {
/* All Main templates are friends */
template<__MAIN_TEMPLATE_PARAMS__> friend class Main;
/* Private stuff, not reachable from the outside */
static void privateThing(){
...
}
};
}
template<__MAIN_TEMPLATE_PARAMS__> class Main {
void usePrivateThing(){
detail::Helper<__DESIRED_HELPER_TEMPLATE_PARAMS__>::privateThing();
}
};
The private stuff is static
above only to make the code shorter. They may very well be tied to the Helper
instance.
In retrospect, there could certainly be more elegant solutions involving less black magic, but it highly depends on the specific application. I still find the above a legit, nice use case for a friend
class.
1 This is because I needed to use a template helper function that required a partial specialization, which is not allowed yet in c++, for no particular reason but is technically possible with a wrapper class. Partial specialization is omitted from the above for simplicity.