Home  >  Article  >  Backend Development  >  How to Declare a Templated Struct as a Friend in C ?

How to Declare a Templated Struct as a Friend in C ?

DDD
DDDOriginal
2024-11-06 15:49:02286browse

How to Declare a Templated Struct as a Friend in C  ?

Templated Struct/Class Declaration as Friend

In C programming, one may encounter scenarios where declaring a templated struct or class as a friend is desired. However, when attempting the common approach below, some compilers, such as Visual C 8 (VC8), raise errors:

template <typename T>
struct foo
{
    template <typename S>
    friend struct foo<S>;
};

The rationale behind this error is the compiler's inability to handle multiple template parameter lists in a single line. To overcome this hindrance, an alternative syntax is introduced:

template <typename> friend class foo;

By specifying an empty template parameter list, the friend declaration now applies to all potential instantiations of the templated struct or class. However, it's worth noting that this approach makes all templates friends with each other. For instance, foo and foo would both be friends, despite your original intent of declaring instances of foo as friends to foo.

The above is the detailed content of How to Declare a Templated Struct as a Friend in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn