Home > Backend Development > C++ > How Can You Declare Templated Structs/Classes as Friends in C ?

How Can You Declare Templated Structs/Classes as Friends in C ?

Linda Hamilton
Release: 2024-11-07 17:40:03
Original
951 people have browsed it

How Can You Declare Templated Structs/Classes as Friends in C  ?

Declaring Templated Structs/Classes as Friends

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:
    // ...
};
Copy after login

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:
    // ...
};
Copy after login

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!

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