Home >Backend Development >C++ >How to Declare a Templated Class or Structure as a Friend?

How to Declare a Templated Class or Structure as a Friend?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 21:47:01933browse

How to Declare a Templated Class or Structure as a Friend?

Templated Class or Structure as Friend Declaration

When attempting to declare a templated struct or class as a friend, you may encounter compilation errors. For instance, consider the following code:

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

private:
    // ...
};

This code fails to compile with an error message indicating that multiple template parameter lists are not allowed. However, you still want all possible instantiations of the foo template struct to be friends of foo for any T.

Solution

To achieve this, you can use the following declaration:

template <typename> friend class foo

This declaration signifies that all template instantiations of the foo class will be friends of all other template instantiations of the foo class.

Additional Note

The declaration

template <typename>
friend struct foo;

will also work, but it makes all template instantiations of the foo struct friends of each other. This is likely the behavior you intend. However, it's worth noting that friend declarations and templates have a somewhat complex syntax.

The above is the detailed content of How to Declare a Templated Class or Structure as a Friend?. 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