Templated Class or Structure as Friend Declaration
When attempting to declare a templated struct or class as a friend, you may encounter compilation errors. For instance, consider the following code:
template <typename T> struct foo { template <typename S> friend struct foo<S>; private: // ... };
This code fails to compile with an error message indicating that multiple template parameter lists are not allowed. However, you still want all possible instantiations of the foo template struct to be friends of foo
Solution
To achieve this, you can use the following declaration:
template <typename> friend class foo
This declaration signifies that all template instantiations of the foo class will be friends of all other template instantiations of the foo class.
Additional Note
The declaration
template <typename> friend struct foo;
will also work, but it makes all template instantiations of the foo struct friends of each other. This is likely the behavior you intend. However, it's worth noting that friend declarations and templates have a somewhat complex syntax.
The above is the detailed content of How to Declare a Templated Class or Structure as a Friend?. For more information, please follow other related articles on the PHP Chinese website!