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

How to Declare a Templated Struct or Class as a Friend in C ?

Mary-Kate Olsen
Release: 2024-11-09 08:49:02
Original
1026 people have browsed it

How to Declare a Templated Struct or Class as a Friend in C  ?

Declaring a Templated Struct or Class as a Friend

In C programming, it is possible to declare a templated struct or class as a friend to another class, effectively allowing access to private members. However, some compilers, such as VC8, may encounter errors when implementing this feature.

Incorrect Syntax:

The following code attempts to declare a templated struct foo as a friend to all other instantiations of foo:

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

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

However, this will result in the error:

error C3857: 'foo<T>': multiple template parameter lists are not allowed
Copy after login

Correct Syntax:

To correctly declare a templated struct or class as a friend, use the following syntax:

template <typename> friend class foo;
Copy after login

This will allow all template instantiations of foo to be friends of each other, as desired. Therefore, the correct code should be:

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

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

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