Declaring a Templated Struct or Class as a Friend
In C programming, it is possible to declare a templated struct or class as a friend to another class, effectively allowing access to private members. However, some compilers, such as VC8, may encounter errors when implementing this feature.
Incorrect Syntax:
The following code attempts to declare a templated struct foo as a friend to all other instantiations of foo:
template <typename T> struct foo { template <typename S> friend struct foo<S>; private: // ... };
However, this will result in the error:
error C3857: 'foo<T>': multiple template parameter lists are not allowed
Correct Syntax:
To correctly declare a templated struct or class as a friend, use the following syntax:
template <typename> friend class foo;
This will allow all template instantiations of foo to be friends of each other, as desired. Therefore, the correct code should be:
template <typename T> struct foo { template <typename> friend class foo; private: // ... };
The above is the detailed content of How to Declare a Templated Struct or Class as a Friend in C ?. For more information, please follow other related articles on the PHP Chinese website!