Home > Backend Development > C++ > body text

How to Declare Templated Structs/Classes as Friends in C ?

Mary-Kate Olsen
Release: 2024-11-07 08:38:02
Original
732 people have browsed it

How to Declare Templated Structs/Classes as Friends in C  ?

Declaring Templated Structs/Classes as Friends

In C , one can face difficulty when declaring templated structs or classes as friends of other templated structs or classes. Consider the following scenario:

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

private:
    // ...
};
Copy after login

Compiling this code in Visual C 8 may trigger error C3857: "multiple template parameter lists are not allowed." This arises from the compiler's inability to handle the nested template declaration within the friend declaration.

To resolve this issue, one can utilize the simplified syntax:

template <typename> friend class foo;
Copy after login

This syntax declares all instances of the templated struct foo as friends of the enclosing foo template. It effectively achieves the intended goal of making all possible instantiations of foo friends of each other.

Note that this approach differs from the original declaration in that it makes all templates friends of each other, regardless of the specific template arguments. This may or may not be the desired behavior, depending on the specific requirements.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!