Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-11-12 21:47:01
Original
885 people have browsed it

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

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
Copy after login

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;
Copy after login

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!

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