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
Linda HamiltonOriginal
2024-11-07 17:40:03991browse

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

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

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!

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