In the realm of C , declaring templated structs or classes as friends can present a syntax-related roadblock. To achieve this, consider the following approach:
template <typename T> struct foo { template <typename> friend class foo; private: // ... };
This syntax appears to compile successfully. However, it declares all template instantiations of foo as friends to each other, regardless of the template parameter they take. This may or may not align with your intended use case.
If you need to limit the friendship to only specific instantiations, you can achieve this using this syntax:
template <typename T> struct foo { template <typename S> friend struct foo<S>; private: // ... };
Unfortunately, this syntax doesn't allow for a generic declaration that includes all possible instantiations of foo.
Therefore, if your goal is to establish friendship across all of foo's template instantiations, the second approach using friend class foo is the closest you can get, given the constraints of C syntax.
The above is the detailed content of How Can You Declare Templated Structs/Classes as Friends in C ?. For more information, please follow other related articles on the PHP Chinese website!